skip to Main Content

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


  1. Chosen as BEST ANSWER

    It was a matter of trial and error since I could never see the value of currentCache, but I realised that I needed to add response.data.data to the currentCache. In the end, the following worked.

    currentCache.data.push(...newItems.data);
    

  2. I assume, you need to make sure currentCache is always an array while performing a spreading operation. you can ensure that currentCache by doing :

    merge: (currentCache = [], newItems) => [...currentCache, ...newItems],
    

    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 of last_page in your component or where you’re dispatching the action to fetch data, and conditionally stop further fetching based on that value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search