Updating query data without access to complete query key
Assume the following scenario:
I have two screens:
Screen1: queries server for restaurants and displays them in a list( favorited restaurants have a heart icon displayed in the ui)
Screen2: displays a single restaurant where the user can toggle the favorite state
The query for the restaurants query looks like the following:
In the query, I add the
longitude and latitude in the query key, sincy in my application these can change and I want to make sure the restaurants list is updated according to it.
My issue is that when a user favorites/unfavorites and I want to mutate the restaurant to reflect this change, but I do not have access to the longitude and latitude values because they are defined in Screen1.
Is there a way to update the restaurants without access to the complete list of query key? I know the query key starts with 'restaurants'.3 Replies
sunny-green•3y ago
queryClient.setQueriesData
correct-apricot•3y ago
That 👆 .
queryClient.setQueriesData accepts a QueryFilters (https://tanstack.com/query/v4/docs/react/guides/filters#query-filters) as first param, so you can pass only a part of the key (in your case 'restaurant') and it will update the data for all the queries that match that filter (the updater function that you pass as second param is called for each match).
Then, in the updater function, you can update only the restaurant with a given id.sensitive-blueOP•3y ago
interesting thank you 🙏🏻