apollo-feature-requests icon indicating copy to clipboard operation
apollo-feature-requests copied to clipboard

Allow to refetchQueries also on error

Open obrejla opened this issue 3 years ago • 2 comments

Hi,

currently, the documentation regarding refetchQueries says that An array or function that allows you to specify which queries you want to refetch after a mutation has occurred. But it's not clear, that "mutation has occurred" in fact mean, "it was successful".

This means, that refetchQueries will not be triggered when an error occurs during mutation. But imho it would be very helpful to allow that, by some option or something. Because currently there is no simple way to refetch query on error. You must pass refetch function from useQuery down to desired component where useMutation is used and it is very uncomfortable.

The problem is, that frontend could be in some "valid" state for triggering mutation, like input fields are enabled etc. But on backend something changes and suddenly it is not valid anymore (and no, sending subscription event to the frontend and disable form fields is not a very user friendly way how to handle that), so what happens...UI sends mutation request, it fails, and on response, it would be great to refetchQueries, so we get new data describing an already "unmodifiable" state.

So I propose to introduce a possibility to allow refetchQueries also for mutations, where an error occurred.

Thanks.

obrejla avatar Apr 13 '21 07:04 obrejla

@obrejla i found this issue because i had the same request, but there might already be a way to achieve the behavior that you want:

  const [mutate, mutationStatus] = Apollo.useMutation(
    YOUR_MUTATION_GQL,
    {
      refetchQueries: [
        {
          // as you point out, this only happens on success, and the docs are misleading about it
          query: YOUR_OTHER_QUERY_GQL,
          variables: {},
        },
      ],
      awaitRefetchQueries: true,
      // but you can refetch a query here too
      onError: () => mutationStatus.client.refetchQueries({ include: [YOUR_OTHER_QUERY_GQL] })
    }
  );

https://www.apollographql.com/docs/react/data/refetching/

nweajoseph avatar Nov 03 '21 16:11 nweajoseph

My use case is slightly different. I wish refetchQueries worked when a failed mutation is retried and succeeds.

In my case, an expired token is the most common cause of errors, so I create the client with an onError link that refreshes the token, then return forward(operation). That means the operation is retried and works the second time. But refetchQueries isn't executed then.

awaitRefetchQueries doesn't seem to make a difference. In any case this should really be enabled globally, probably by default.

dalmo3 avatar Mar 09 '22 21:03 dalmo3