2

I have an issue where we're using apollo client and specifically the useMutation react hook to perform mutation calls to our GraphQL Server. At certain times, the server may return a 401 unauthorized response - at which point, we can make a call to special endpoint which re-authenticates the client and refreshes the cookie/token whatever. I want to be able to re-run the same mutation again once the client is re-authenticated. So basically I would like to know if it is possible to do the following: useMutation --> Receive 401 Unauthorized --> call to refresh token --> rerun same initial mutation This is how our useMutation looks like:

 const [mutationFunction, { data, ...rest }] = useMutation(query, {
    onError(_err: any) {
        const networkError = error?.networkError as any;
        if (networkError?.statusCode === 401 && !refreshFailed) {
            // eslint-disable-next-line prefer-destructuring
            loading = true;
            error = undefined;

            fetch('/authentication/refresh', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            })
                .then(response => response.json())
                .then(token => {
                    localStorage.setItem(jwtLocalStorageKey, token);
                    // re fetch here
                })
                .catch(() => {
                    refreshFailed = true;
                });
        } else {
            showAlert(_err.message, 'error');
        }
    }
});

and this is how we call it currently:

  const {
    mutationFunction: updateTournamentUserMutation,
    loading: updateTournamentUserLoading,
    error: updateTournamentUserError,
    data: updateTournamentUserData
} = useMutationHook(gqlUpdateTournamentUser);

 updateTournamentUserMutation({ variables: { input } });

Because we're using hooks and the way we're using it above, I'm not entirely sure how we can save or reuse the same data that is initially sent in the first mutation (that is the mutation parameters) Is it possible to do so using the current way we're doing it?

0 Answers0