F
F
frogqwetr2022-03-11 19:24:54
React
frogqwetr, 2022-03-11 19:24:54

How to make pagination using RTK Query?

I want to make pagination (infinite scroll) using RTK Query, but I don't understand how to do it correctly. I get a limited list of users and when I click on the "show more" button, my page changes, but the old data that was received before is overwritten. Is it possible to somehow get the status of all previously sent requests? Or add them yourself, as is done with the usual approach, for example, using redux-thunk and other tools.
User list component

const UsersList: FC = memo(() => {
    const [page, setPage] = useState(1)
    
     const {isLoading, data } = useGetInformationAboutAllUsersQuery(page)
   
    const users = !isLoading && data?.usersInformations ? 
                  <List items={data.usersInformations} renderItem={renderUserItem} />: null

    return (
        <div>
            {users}
            <button onClick={()=>setPage(page => page+1)}>Показать еще</button>
        </div>
    )
})

RTK Query.

interface IDataUsersQuery{
    usersInformations: IUserInformation[],
    totalCount: number | undefined
}

export const usersSliceQuery = createApi({
    reducerPath:'users',
    baseQuery: fetchBaseQuery({baseUrl: apiUrlNames.MAIN_URL}),
    tagTypes: ['users'],
    endpoints: (builder) => ({
        getInformationAboutAllUsers: builder.query<IDataUsersQuery, number>({

            query: (page : number = 3 ) => {
               return `${apiUrlNames.URL_USERS_INFORMATIONS}?_limit=${5}&_page=${page}`
            },

            transformResponse(response: IUserInformation[], meta: any) {
                return { usersInformations: response, 
                    totalCount: Number(meta?.response?.headers.get('X-Total-Count')) }
              }
        })
    })
})

export const {useGetInformationAboutAllUsersQuery} = usersSliceQuery

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mark Chigrin, 2022-03-13
@frogqwetr

For this case, there is no ready-made solution inside the library - feature discussion on github
- You can use React Query (useQueries)
- Use only 3 pages (prev, current, next)
- Write your own hook on top of rtq. Made an example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question