Creating paginated queries
When building an API to deal with large datasets, to avoid having your frontend deal with everything at once, you don’t want to send all the available data in one request. A pattern often used to make this easier is API pagination.
If your API is paginated, you want to apply the same pattern to your application.
The good thing is that you only need to use useQuery
and one of its options, keepPreviousData
.
Let’s look at the next examples and then understand how pagination and React Query work. First, we start with our query function:
const fetchData = async ({ queryKey }) => { const { page } = queryKey[0]; const { data } = await axios.get( `https://danieljcafonso.builtwithdark.com/ react-query-paginated?page=${page}&results=10` ); return data; };
In the preceding snippet, we create the function that will be used as...