Pagination
Pagination
RTK Query does not include any built-in pagination behavior. However, RTK Query does make it straightforward to integrate with a standard index-based pagination API. This is the most common form of pagination that you'll need to implement.
Pagination Recipes
Setup an endpoint to accept a page arg
argimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
interface Post {
id: number
name: string
}
interface ListResponse<T> {
page: number
per_page: number
total: number
total_pages: number
data: T[]
}
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
endpoints: (builder) => ({
listPosts: builder.query<ListResponse<Post>, number | void>({
query: (page = 1) => `posts?page=${page}`,
}),
}),
})
export const { useListPostsQuery } = apiTrigger the next page by incrementing the page state variable
page state variableGeneral Pagination Example
In the following example, you'll see Loading on the initial query, but then as you move forward we'll use the next/previous buttons as a fetching indicator while any non-cached query is performed. When you go back, the cached data will be served instantaneously.
Last updated
Was this helpful?