T
TanStack•3y ago
quickest-silver

Mutate a paginated cache for optimistic updates

Hello, Has anybody managed to pull it off successfully? It seems to be a bit too complicated to insert/delete a record if the cache is paginated
6 Replies
absent-sapphire
absent-sapphire•3y ago
paginated in terms of multiple keys, or paginated in terms of an infinite query with multiple pages inside the same key?
quickest-silver
quickest-silverOP•3y ago
Paginated in terms of multiple keys, something along the lines of: ['tournaments', 1], ['tournaments, 2] And so on and so forth
absent-sapphire
absent-sapphire•3y ago
okay, so if you don't know where the tournament is located (on which page), you'd have to iterate over all of them. setQueriesData would work:
queryClient.setQueriesData(
['tournaments'],
(prev) => {
return prev?.map(tournament => tournament.id === myId ? updatedData : tournament)
}
)
queryClient.setQueriesData(
['tournaments'],
(prev) => {
return prev?.map(tournament => tournament.id === myId ? updatedData : tournament)
}
)
this will iterate over all pages (fuzziliy matching ['tournaments']), then iterate over each entry in each page and update the one found by id. this implies that all pages the same structure, but this is usually true with paginated queries
quickest-silver
quickest-silverOP•3y ago
Thank you so much for the answer, What about the case where i want to insert a new record? Assuming that the record is to be added right at the top of the list - will react-query take care of making sure that all the following data is shifted accordingly? Or is that something i should take care of manually?
absent-sapphire
absent-sapphire•3y ago
react query does nothing of the sorts 😉 that's why invalidation is often preferred - it refetches, and then things are they were they are on the server. with manual updates, you have to mimic the server behaviour on the client
quickest-silver
quickest-silverOP•3y ago
Thanks again, i appreciate the help!

Did you find this page helpful?