Axios cancelToken in useEffect cleanup

Viewed 77

I would like to implement Axios cancel token through useEffect cleanup code, I can implement this way when calling the axios in the component, however I would like to know if I can implement cancelToken when axios call is in separate file.

[when using axios in the component] 
useEffect(() => {
const request = Axios.CancelToken.source() 

const fetchPost = async () => {
  try {
    const response = await Axios.get(`endpointURL`, {
      cancelToken: request.token, 
    })
    setPost(response.data)
    setIsLoading(false)
  } catch (err) {
    console.log('There was a problem or request was cancelled.')
  }
}
fetchPost()

return () => request.cancel() 
}, [])
[page component]
  useEffect(() => {
    const cancel = axios.CancelToken.source();
    fetchData();
    return () => {
};
  }, []);

  const fetchData= async () => {
    try {
      const payload = {
        page: 0,
        size: 10,
      };
      const {
        data: { content },
      } = await UserService.getUserSupplier(payload);
      setSupplier(content);
    } catch (err) {
      console.log(err);
    }
  };

[UserService.js]
export const getUserSupplier = async payload => {
  const url = `/user/supplier?${qs.stringify(payload)}`;
  const response = await ApiService.get(url); // ApiService is just Axios I separated file because of interceptor 
  return response;
};
0 Answers
Related