redux-toolkit
redux-toolkit copied to clipboard
RTK Query - endpoint args not updated when using merge with refetch
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
Sorry, I don't think I have enough context to understand what you're trying to do. Could you put together a CodeSandbox or a Replay ( https://replay.io/record-bugs )?
I've created a repo on GitHub: https://github.com/v-x2/RTKIssue/tree/main
@v-x2 not sure what is your intention, but I noticed that your forceRefetch seems wrong.
forceRefetch({ currentArg, previousArg }) {
return currentArg !== previousArg
},
Result of this statement is always true as you do referential equality for objects. So either you need to make your args momoised or change statement to return currentArg.lastKey !== previousArg?.lastKey
Thanks for you answer!
Yes, the statement is always true so it should refetch each time. The problem is that is not refetching anything...
I've tried to add a console.log to see the Status of the request and is always stuck at pending
useEffect( () => {
console.log(status)
}, [status])
any updates?
Looking at this, I think the suggestion today would be to use the recent infinite query support, which ought to handle this better.