#How to avoid re-fetching query after resource is deleted

1 messages · Page 1 of 1 (latest)

safe laurel
#

The user is on a page with multiple items (query ["items"]) and has one items selected that shows more details (query ["items", id]) and the selected id is stored in the URL as search param.

Now the user deletes the currently selected item which triggers a mutation in a child component.

  1. The mutation hook then invalidates ["items"] in the onSuccess callback.
  2. The child component uses the separate onSuccess callback of the mutate function to let the parent know that the resource was deleted.
  3. The parent component removes the id from the search params and React Router re-renders the page without item details.

The problem is that the deleted item query ["items", id] will be re-fetched before the router has re-rendered the page, resulting in a 404.
The query invalidation is necessary because the list of items should be re-fetched (and we don't want to have deleted data in the cache).

What's a good approach to handle such a case?

safe laurel
#

I guess I could use mutation keys and useMutationState in the query hook to disable the query during / after mutation, but not sure if that's the best way.

safe laurel
#

I now use a different approach: I exclude the query of the deleted resource via predicate and invalidate it separately but disable refetch for it.

If anyone knows a better approach let me know.

potent raptor
#

If you fetch based on the search params and the parsed search params are part of your useQuery key you don't have to invalidate and it will refetch onSuccess due to changed query input. You can keep the loading state of the mutation if you wrap your onSuccess in an async and await your own on success callback.

safe laurel
# potent raptor If you fetch based on the search params and the parsed search params are part of...

you don't have to invalidate

Invalidating the list of items will automatically invalidate the deleted item.

if you wrap your onSuccess in an async and await your own on success callback.

What what you await here? The component just calls the onSuccess callback from the parent but this callback doesn't return a promise (and it can't because React Router doesn't return anything either when updating the params).

proper phoenix
#

Hey @safe laurel, I am having a similar issue to you right now. I have Axios setup with an interceptor that automatically catches certain errors and displays a toast. Every time I delete something like ['contacts', 1], I get a 404 error toast over and over because I assume it's trying to refetch it.

How did you go about solving this in the end?

safe laurel