redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

RTK Query - endpoint args not updated when using merge with refetch

Open v-x2 opened this issue 2 years ago • 5 comments

Hi,

I'm implementing pagination with RTK Query (1.9.0) but dunno why if, at the end of the page, I refetch using the next page, the query is executed without the previous lastKey (which in the first page is undefined).

getLatestTravels: builder.query<Page<Travel>, PagedRequest>({
            query: ({limit, lastKey,}) => {
               
                log.warn(lastKey)
                let url = `/travels/latest?limit=${limit}`
                if(lastKey) {
                    url += `&lastKey=${lastKey}`
                }
                return ({
                    url: url,
                    method: "GET"
                })
            },

            merge: (currentCacheData, responseData) => {
                if(!responseData?.data) {
                    return
                }
                log.error(responseData?.lastKey)
                currentCacheData.lastKey = responseData?.lastKey
                currentCacheData.count = responseData.count
            },
            serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
                const { lastKey, limit } = queryArgs
                return endpointName
            },
            forceRefetch({ currentArg, previousArg }) {
                return currentArg !== previousArg
            },
            providesTags: (result, error, arg) => {
                return result
                    ? [{type: "LatestTravels", lastKey: arg?.lastKey}]
                    : ['LatestTravels']
            }
        }),

In my React component, when the end of the list is reached the following function is executed:

const onNextPage = useCallback( () => {
        if(data?.lastKey) {
            log.warn("Refetching with LastKey: " + data?.lastKey)
            refetch()
        }
    }, [data])

The third row should contain the lastKey params...

 LOG  11:29:06 PM | INFO : GET ➞ /travels/latest?limit=5 ===> 200 
 LOG  11:29:07 PM | WARN : Refetching with LastKey: 636821cd2b6107b94c2f0ffd 
 LOG  11:29:07 PM | INFO : GET ➞ /travels/latest?limit=5 ===> 200 
 LOG  11:29:07 PM | ERROR : 636821cd2b6107b94c2f0ffd 

v-x2 avatar Nov 07 '22 22:11 v-x2