techStackGuru

React Native Flatlist Pagination


The pagination process in React Native involves displaying a long list of items on a series of pages to improve performance. It is commonly used when loading all items from an API would be inefficient or impractical.

import React, { useState, useEffect } from 'react';
import { View, FlatList, Button, ActivityIndicator } from 'react-native';

const MyComponent = () => {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [totalPages, setTotalPages] = useState(0);

  useEffect(() => {
    fetchData();
  }, [page]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const response = await fetch(`https://api.example.com/data?page=${page}`);
      const jsonData = await response.json();
      setData(prevData => [...prevData, ...jsonData.data]);
      setTotalPages(jsonData.totalPages);
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleLoadMore = () => {
    if (!loading && page < totalPages) {
      setPage(page + 1);
    }
  };

  return (
    <View>
      <FlatList
        data={data}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          /* Render your item here */
          <Text>{item.name}</Text>
        )}
        onEndReached={handleLoadMore}
        onEndReachedThreshold={0.1}
        ListFooterComponent={loading && <ActivityIndicator />}
      />
    </View>
  );
};

export default MyComponent;

The following example illustrates:

  • data contains the API-fetched items.
  • page keeps track of the page number that is currently displayed.
  • loading indicates whether data is being retrieved.
  • totalPages keeps track of the total number of pages.
  • fetchData function retrieves data from the API based on the current page.
  • handleLoadMore method is called when a user reaches the end of the list, which triggers the loading of the next page.