calling useState setter function after async API call

Viewed 50
  const [inventory, setInventory] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const apiCall = async () => {
      try {
        const products = await axios.get("/product");
        setInventory(products.data);
      } catch (e) {
        setError(e);
      }
    };
    apiCall();
  }, []);

Is the above code bug free?

What if after the promise resolves but the component that contains this code has been destroyed.

Hence, both the setInventory and setError variables will then be undefined, rather than setter function. So calling undefined as a function will throw an error.

The error thrown in the try block will be caught in the catch block. But the catch block will also throw an error as setError is no longer a function?

1 Answers

When you attempt to update the state of a component after its been unmounted, React will warn you that you should not do that. This can happen if you perform an asynchronous side effect (such as loading data) and then unmount the component before the asynchronous function is finished. When using React's useEffect hook, you can keep track of whether the component is mounted and then conditionally update state. This happens within the useEffect body:

React.useEffect(() => {
  let unmounted = false;
  setTimeout(() => {
    if (!unmounted) {
      // update state here...
    }
  }, 3000);
 
  return () => {
    unmounted = true;
  };
});

read from: owenconti.com...... https://owenconti.com/posts/how-to-fix-cannot-update-unmounted-component-warning-with-react-hooks#:~:text=When%20you%20attempt%20to%20update,the%20asynchronous%20function%20is%20finished.&text=10%20unmounted%20%3D%20true%3B,11%20%7D%3B

Related