setQueryData returned by useQuery
Thoughts on returning a function from useQuery that sets the specific query data in a “safe” way?
4 Replies
jolly-crimson•3y ago
has been asked for multiple times in the past. would be totally possible - but I wouldn't know a case where I'd actually need that. What would you need it for?
generous-apricotOP•3y ago
In my case - would like to ensure that the variables passed to setQueryData are correct 100% of the time and the type of data passed is correct 100% of the time
Also misspellings in the queryKey at index 0 would never happen
Would eliminate a wide variety of bugs from even having a chance to occur. In your usage of setQueryData do you not find it at least a bit off putting to be able to make so many mistakes and not take advantage of type checking?
Or is there another way you accomplish that
jolly-crimson•3y ago
for key, query key factories are recommended: https://tkdodo.eu/blog/effective-react-query-keys
you can also pass a generic to
setQueryData
and create your own wrapper to achieve this.
what I wanted to hint towards is that in places where you call setQueryData
, like a callback of a mutation, you likely won't have access to setData
returned from useQuery
anyways, because your mutation very likely lives in a different place, or at least, in a custom hook. Consider:
now how would you get access to setData
returned from useQuery
here? Even if your query and your mutation live in the same component, which they often won't, you would have to pass that function to the mutation. I don't see how that's so much betterEffective React Query Keys
Learn how to structure React Query Keys effectively as your App grows
generous-apricotOP•3y ago
@TkDodo 🔮
Excellent, i understand and agree with the shortcomings of the method I originally asked about