乐闻世界logo
搜索文章和话题

How to implement infinite list using React Query in react native with Flatlist

1个答案

1

To implement an infinite scroll list using React Query and the FlatList component in a React Native project, follow these steps:

Step 1: Installing and Setting Up React Query

First, ensure that you have installed React Query. If not, add it using npm or yarn.

bash
npm install react-query # or yarn add react-query

Step 2: Setting Up the React Query Client

In your project, create a React Query client instance and wrap your application with QueryClientProvider.

jsx
import { QueryClient, QueryClientProvider } from 'react-query'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> <MyComponent /> </QueryClientProvider> ); }

Step 3: Using useInfiniteQuery to Fetch Data

The useInfiniteQuery hook from React Query is well-suited for implementing infinite scrolling. This hook helps load more data when the user is near the bottom of the list.

First, define a function to fetch data that accepts the current page number as a parameter.

javascript
const fetchProjects = ({ pageParam = 1 }) => { return fetch(`https://api.example.com/projects?page=${pageParam}`) .then(res => res.json()); }

Then, use useInfiniteQuery in your component:

jsx
import { useInfiniteQuery } from 'react-query'; function Projects() { const { data, fetchNextPage, hasNextPage, isFetchingNextPage, } = useInfiniteQuery('projects', fetchProjects, { getNextPageParam: (lastPage, pages) => lastPage.nextPage ?? false, }); return ( <FlatList data={data.pages.flatMap(page => page.results)} onEndReached={() => hasNextPage && fetchNextPage()} onEndReachedThreshold={0.5} keyExtractor={(item) => item.id.toString()} renderItem={({ item }) => ( <Text>{item.name}</Text> )} ListFooterComponent={ isFetchingNextPage ? <ActivityIndicator /> : null } /> ); }

Explanation:

  • fetchProjects: This is a function that calls the API to fetch data.
  • useInfiniteQuery: This hook implements infinite loading by determining if additional pages are needed through getNextPageParam.
  • FlatList component: The FlatList from React Native renders the list and accepts an onEndReached callback that triggers when scrolling near the bottom. Use this property to call fetchNextPage for loading more data.
  • ListFooterComponent: An activity indicator can be displayed while fetching the next page of data.

This is the basic process for implementing infinite scroll lists in a React Native project using React Query and the FlatList component. This approach effectively handles large data loads while maintaining a good user experience.

2024年8月5日 11:18 回复

你的答案