I have paged data from my server that I’d like to display in an endless scroll. I know I can manage it with pure redux, but I’d like to be able to do it with Redux Toolkit. I’ve tried reading https://github.com/reduxjs/redux-toolkit/discussions/1163?sort=new, but I don’t understand the way people have done this. RTK’s merge
seems the most promising option https://redux-toolkit.js.org/rtk-query/api/createApi#merge but so far my implementation just overwrites the existing data with the new page rather than appending it.
The code as per the merge
example in the official documentation:
query: ({accountId, page}) => {
console.log('accountId', accountId);
return {
url: `/api/transactions/account/${accountId}`,
method: 'get',
params: {page}
}
},
serializeQueryArgs: ({endpointName}) => {
return endpointName
},
merge: (currentCache, newItems) => {
currentCache.push(...newItems)
},
forceRefetch({ currentArg, previousArg}) {
return currentArg !== previousArg;
},
}),
gives me an error TypeError: Spread syntax requires ...iterable[Symbol.iterator] to be a function
for currentCache.push(...newItems)
I’ve swapped this out for return [...currentCache, ...newItems]
, but this tells me that TypeError: currentCache is not iterable
What should I try next? The data is in response.data.data
, which might be confusing things a bit. I’d also want access to response.data.last_page
so I know when to stop fetching data.
2
Answers
It was a matter of trial and error since I could never see the value of
currentCache
, but I realised that I needed to addresponse.data.data
to the currentCache. In the end, the following worked.I assume, you need to make sure currentCache is always an array while performing a spreading operation. you can ensure that currentCache by doing :
Additionally, to access
response.data.last_page
and stop fetching data when needed, you might need to adjust your logic outside of the merge function. You can check the value oflast_page
in your component or where you’re dispatching the action to fetch data, and conditionally stop further fetching based on that value.