1
unknown
plain_text
a year ago
3.2 kB
1
Indexable
Never
import React, { useState, useEffect } from "react"; import { StyleSheet, View, FlatList, Text, ActivityIndicator } from "react-native"; export default function App() { // Write your logic here... const [data, setData] = useState([]); // state to store the list of country names const [loading, setLoading] = useState(false); // state to indicate if data is being fetched const [offset, setOffset] = useState(0); // state to keep track of the current offset const [count, setCount] = useState(0); // state to store the total number of countries in the API // function to fetch data from the API const fetchData = async () => { setLoading(true); // set loading to true before fetching data try { // make a GET request with the offset and limit parameters let response = await fetch( `https://example.com/countries?offset=${offset}&limit=20` ); let json = await response.json(); // parse the response as JSON setData([...data, ...json.results]); // append the new data to the existing data setOffset(offset + 20); // increment the offset by 20 setCount(json.count); // set the count to the value returned by the API } catch (error) { console.error(error); // log any error } setLoading(false); // set loading to false after fetching data }; // function to render each item in the list const renderItem = ({ item }) => { return ( <View style={styles.listItem}> <Text>{item.name}</Text> </View> ); }; // function to render the footer of the list const renderFooter = () => { if (loading) { return <ActivityIndicator size="large" color="#0000ff" />; // show a loader if data is being fetched } else { return null; // otherwise return nothing } }; // function to check if the end of the list is reached const isEndReached = () => { return offset >= count; // return true if offset is equal or greater than count }; // function to handle the end reached event of the list const handleEndReached = () => { if (!loading && !isEndReached()) { fetchData(); // fetch more data if not loading and not end reached } }; useEffect(() => { fetchData(); // fetch initial data when the component mounts }, []); // run only once return ( <View style={styles.container}> <FlatList style={styles.list} data={data} // pass the data as a prop renderItem={renderItem} // pass the renderItem function as a prop ListFooterComponent={renderFooter} // pass the renderFooter function as a prop onEndReached={handleEndReached} // pass the handleEndReached function as a prop onEndReachedThreshold={0.1} // set the threshold to trigger onEndReached at 10% of content left /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center", }, list: { width: "100%", height: "100%", }, listItem: { width: "100%", height: "40px", padding: "8px", alignItems: "flexStart", justifyContent: "center", borderBottomWidth: 1, borderBottomColor: "#ccc", }, });