justanotherguy
justanotherguy

Reputation: 414

Cancel Axios request in useEffect not running

I am attempting to cancel an axios request, but I am only having partial success. I have this function that returns a Promise when I make a GET request:

const getCards = (token) => {
  const URL = isDev
    ? "https://cors-anywhere.herokuapp.com/https://privacy.com/api/v1/card"
    : "https://privacy.com/api/v1/card";
  const config = {
    headers: {
      Authorization: `Bearer ${token}`,
    },
    cancelToken: source.token,
  };

  return axios.get(URL, config);
};

I call this function inside updateCards() which looks like this:

const updateCards = async () => {
  console.log("Updating Cards");

  setCards([]);
  setStarted(true);
  setLoading(true);

  let response = await getCards(token).catch((thrown) => {
    if (axios.isCancel(thrown)) {
      console.error("[UpdateCards]", thrown.message);
    }
  });

  /**
   * response is undefined when we cancel the request on unmount
   */

  if (typeof response === "undefined") return console.log("Undefined");

  console.log("Got Response from UpdateCards", response);

  setLoading(false);
};

I cancel my request in the useEffect hook as so:

useEffect(() => {
    return () => {
        source.cancel()
    }
}, [])

And I have setup my CancelToken under my state declaration like this:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

My issue is that, if I call my updateCards() function inside of the useEffect(), I can cancel it just fine, but if I use a button to call that same function the cancel is not ran. I have looked everywhere and the only solution I have found is that I have to call my requests within the useEffect() hook, but that is not something I want to do.Where do I go from here?

Here are the resources I have looked at:

https://github.com/axios/axios#cancellation

https://medium.com/@selvaganesh93/how-to-clean-up-subscriptions-in-react-components-using-abortcontroller-72335f19b6f7

Cant cancel Axios post request via CancelToken

Upvotes: 3

Views: 2855

Answers (1)

Ross Allen
Ross Allen

Reputation: 44900

To have a place to store a variable that behaves like an instance variable of the component, you can use useRef. It's a container for anything you want. You can store the CancelToken in there:

function Privacy(props) {
  const source = useRef(null);

  function getSource() {
    if (source.current == null) {
      const CancelToken = axios.CancelToken;
      source.current = CancelToken.source();
    }
    return source.current;
  }

  useEffect(() => {
    return () => {
      if (source.current != null) source.current.cancel();
    }
  }, [])

  // call `getSource()` wherever you need the Axios source
}

Upvotes: 6

Related Questions