'cleanup function cancelling all requests with axios and cancel token

I am trying the following example, so my useEffect, which renders 9 times, only sends a request once. I am using CancelToken from axios for that along the clean up function. I have found this example;

useEffect(() => {
  const CancelToken = axios.CancelToken;
  const source = CancelToken.source();
  axios
    .get(API, {
      cancelToken: source.token
    })
    .catch((err) => {
      if (axios.isCancel(err)) {
        console.log('successfully aborted');
      } else {
        // handle error
      }
    });
  return () => {
    // cancel the request before component unmounts
    source.cancel();
  };
}, []);

I found here in my own code.

  useEffect(() => {
    var source = axios.CancelToken.source();

    if (currentPosts.first_date == undefined) {
      axios
        .get(
          "/api/main/posts/show.json",
          {cancelToken: source.token}
        )
        .then((response) => {
          if (isApiSubscribed) {
            setSelectedDate(response.data?.currentPosts?.current_time);
          }
        })
        .catch((err) => {
          if (axios.isCancel(err)) {
            console.log("successfully aborted");
          } else {
            // handle error
          }
        });
    }

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

But when I apply it, it cancels every single request. What am I doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source