Loading

Best way of integrating load more using Flatlist in React-Native

Best way of integrating load more using Flatlist in React-Native

Sometimes our app takes too much time to display data on the mobile screen and it is due to load the list of data all at once. We can manage them by integrating pagination into our app. But pagination is the old technique in recent times to handle this. Instead, we can use FlatList which displays a scrolling list of changing data in a similar structured way.

FlatList works perfect for long lists of data, where the number of items might change over time. FlatList doesn't render the elements all at once, it only renders the elements which are currently showing on the screen.

To get a clear view let's take an example to understand this.

Step1: In the below example we have taken three state variables and set them with their default values.

const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
const [page, setPage] = useState(1);

Step2: Inside the useEffect() we have set loading to true so that loader can be shown while fetching data through api and then set false to stop loader once fetching is completed.

useEffect(() => {
    setLoading(true);
    _callDataFetching();
}, [page]);


const _callDataFetching = () => {
    axios.get(`https://jsonplaceholder.typicode.com/photos?_limit=5&_page=${page}`)
          .then(response => {
            // handle success
            setLoading(false);
            setBookings(bookings);
        })
          .catch(error => {
            // handle error
            console.log(error);
          })
          .then(() => {
                // always executed
          });
};

You may also like: React - Basic Form building and validation with Formik and Yup

Step3: The FlatList requires at least two props data and renderItem. Where data is to hold the source of data fetched from the api depending on the page value for the list and renderItem takes one item from the source and returns a formatted component to render.

const renderFooter = () => {
    return (
        <Loader loading={loading} />
    )
}

const ListEmptyView = () => {
    return (
        <View style={[{backgroundColor: theme.container},styles.container]}>
            <Text style={styles.emptyRec}>Sorry, no record found</Text>
        </View>
    );
}

const handleLodeMore = () => {
    setPage(page + 1);
}

const renderItem = ({ item }) => (
    <View>
        <Text>{item.title}</Text>
    </View>
);

return (
    <FlatList
        showsVerticalScrollIndicator={false}
        data={bookings}
        renderItem={renderItem}
        keyExtractor={(item, index) => index.toString()}
        ListEmptyComponent={ListEmptyView}
        onEndReached={handleLodeMore}
        onEndReachedThreshold={0.5}
        ListFooterComponent={renderFooter}
    />
)

From the above you can see we have taken some extra props to integrate the load more option. Let's discuss the purpose of the each prop:

# ListEmptyComponent

It's rendered when the list is empty. It can be a React Component or a React element. In our example we have used ListEmptyView() to display No record found if no data returned from the api.

# ListFooterComponent

Rendered at the bottom of all the items and it can be a React Component or a React element. We have placed our Loader component here.

# keyExtractor

(item: object, index: number) => string;

It is used to extract a unique key to identify each item. Key is used for caching and as the react key to track item re-ordering.

# onEndReached

(info: {distanceFromEnd: number}) => void

It is called once when the scroll position gets within onEndReachedThreshold of the rendered content. Here, on the handleLodeMore() we are incrementing the page state value by 1. If you look at useEffect() carefully, we have set page as a dependency parameter to ensure useEffect() would only call on page value change. Once useEffect() gets called it will show the loader first and then fetch the next set of data through the api depending on the page value.

# onEndReachedThreshold How far from the end (in units of visible length of the list) the bottom edge of the list must be from the end of the content to trigger the onEndReached callback. Thus a value of 0.5 will trigger onEndReached when the end of the content is within half the visible length of the list.

And that's all. Enjoy!!!

You may also like: Lazy Loading with React Suspense

Related Articles

Leave a Reply

Comments