how to invalidate w/o refetching all data
New to react-query, and wanting to know how I can invalidate query w/o needing to refetch all data. E.g., if just adding a caption to a post (one of many), no need to incur the expense of a full requery, but this is precisely what react-query is doing when calling invalidate. Surely there's a more efficient way, but not popping for me reading the docs. Any advice much appreciated. Thanks!
4 Replies
afraid-scarlet•3y ago
If you don't want to refetch the query, you could optimistically update it
optimistic-goldOP•3y ago
Thanks for the suggestion. Even w/ an optimistic update, a requery is needed in case the mutation fails. Being new to react-query, my mental model may need some adjusting, but I'd think there's a way I can parameterize a query on mutation such that the cache data is "patched" instead of needing to refetch all the data just because a user liked a post. Seems horribly inefficient which is why I'm assuming I'm missing a core concept.
conscious-sapphire•3y ago
Even w/ an optimistic update, a requery is needed in case the mutation fails.If the mutation fails you can "revert" the optimistic update. The optimistic update page shows how to do that: https://tanstack.com/query/v4/docs/react/guides/optimistic-updates
Optimistic Updates | TanStack Query Docs
When you optimistically update your state before performing a mutation, there is a chance that the mutation will fail. In most of these failure cases, you can just trigger a refetch for your optimistic queries to revert them to their true server state. In some circumstances though, refetching may not work correctly and the mutation error could ...
optimistic-goldOP•3y ago
Aha. Thank you. I took a closer look at the doc and setQueryData is what I failed to consider -- give me a chance to patch they query state on client.