I am trying to abort the previous requests before the new one with AbortController and useMutation. Here is the sample code:

const controller = useRef(new AbortController());

const [mutationFunction, result] = useMutation(THE_MUTATION,
      {
        context: {
          fetchOptions:
            {
              signal: controller.current.signal,
            },
        },
      });

const handleRequest = () => {
    controller.current.abort();
    controller.current = new AbortController();
    await mutationFunction();
}

This causes the mutationFunction to never run because somehow the abort occurs for the current request and the reassignment of the AbortController does not change a thing. I tried the same with useState, like const [controller, setController] = useState(new AbortController()) and I get the same result. The only thing that worked is adding an await to the setController(new AbortController) line, which is incorrect as the set function of the useState does not return promise. Here is the code:

const [controller, setController] = useState(new AbortController());

const [mutationFunction, result] = useMutation(THE_MUTATION,
      {
        context: {
          fetchOptions:
            {
              signal: controller.signal,
            },
        },
      });

const handleRequest = async () => {
    controller.abort();
    await setController(new AbortController());
    await mutationFunction();
}

Any suggestions of why this first example doesn't work? Why the await solution works? Does anyone know a working way of cancelling the previous requests for Apollo client?

1

There are 1 answers

1
Michel Floyd On

I believe what you're looking for is the reset function of a mutation.

const [mutationFunction, {data, error, reset}] = useMutation(THE_MUTATION,options);

Then when you want to reset a mutation you just invoke reset()

This resets the react state but does not cancel or reverse the mutation on the server.