0

It was an custom hook for handling http request. The problem is when an http request send and while waiting, when the component unmount is shows

** index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. in Login (created by Context.Consumer) **

But i added an request cancel to the axios and when the component unmounts it cancels the request, still it shows above message

import Axios from "axios";

import axios from "../../util/axios";

export const useHttpClient = () => {
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const source = useRef<any>();

  const httpClient =useCallback(async (
    data: any,
    url : string,
    method: "post" | "get" | "patch" | "delete",
    token: string | null
  ) => {

     source.current = Axios.CancelToken.source();

    let response;

    setIsLoading(true);
    let headers;
    if (token) {
      headers = {
        Authorization: "Bearer " + token,
      };
    }

    try {
       response = await axios({url,method, data, headers , cancelToken : source.current.token});
      setIsLoading(false);
      return response;
    } catch (err) {
       if(Axios.isCancel(err)) console.log("Axios error");
      setError("Something went wrong");
      setIsLoading(false);
      throw new Error("Something went wrong");
    }
  },[]);

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

  const resetError = () => {
    setError(null);
  };

  const resetLoading = () => {
    setIsLoading(false);
  };

  return [error, resetError, isLoading, resetLoading, httpClient] as const;
};
  • In order to prevent above error, you also need to abort setting state (`setIsLoading`, `setError`), if the component already has been unmounted - canceling the request with axios is not enough. [Here](https://stackoverflow.com/a/60907638/5669456) is one possible solution. – ford04 Jun 23 '20 at 11:32
  • 1
    Hey @ford04, really thank you. It worked like a charm. I did the same in the component I use this hook. Then it stopped showing memory leak – Scriptii Demon Jun 23 '20 at 13:23

0 Answers0