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?