0

I need your help. I have a component that retrieves data from a REST and when the response returns, I enable the button for the PDF.

const [pdf, setPDF] = useState(false);
const [utente, setUtente] = useState(null);

useEffect(() => {
    const url = ""
    axios.get(url, {
        params: {
            id: props.id
        }
    })
        .then((response) => {
            setPDF(true);
            setUtente(response);
        })
        .catch((err) => {
            setPDF(false);
            setUtente(null);
        });
    return () => {

    };
}, [props.id]);

return (
    <div className="container">
        {
        loadPDF
        ?
        <PDFDownloadLink document={<ComponentPDF utente={utente} />} fileName="utente.pdf">
            { <img src="pdf.png" title="PDF" alt="PDF" /> }
        </PDFDownloadLink>
         :
        <React.Fragment/>
        }
    </div >
);

it works well, but if I go back to the home, sometimes I get this error:

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 the componentWillUnmount method. in InternalBlobProvider (created by PDFDownloadLink)

can someone help me?


I tried the solutions you indicated, but I still have the same error. My "loadPDF" value is true, this is because I received the response from AXIOS.

If after receiving the response from AXIOS I wait a few seconds and then i go back with browser, I don't have this error.

if after the AXIOS reply I go back with the browser, I received this and error. this is because inside Component PDF there is a lot of logic and maybe it takes some time.

do I have to work in ComponentePDF?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Xenoriss
  • 11
  • 2
  • Does this answer your question? [React-hooks. Can't perform a React state update on an unmounted component](https://stackoverflow.com/questions/56442582/react-hooks-cant-perform-a-react-state-update-on-an-unmounted-component) – Mahdi N Apr 21 '20 at 13:14

1 Answers1

1

What's happening is that React tries to update state when the component is unmounted, so we need to cancel the Axios request when the component unmounts.

I'm gonna destructure id from props for simplicity. Also, you can check Cancellation docs from Axios on how to do it, but I'll leave you the following example:

useEffect(() => {
    const url = '';

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

    axios
      .get(url, {
        params: { id },
        cancelToken: source.token,
      })
      .then((response) => {
        setPDF(true);
        setUtente(response);
      })
      .catch((err) => {
        setPDF(false);
        setUtente(null);
      });

    return () => source.cancel();
  }, [id]);
lndgalante
  • 402
  • 2
  • 4