1
// Fetch Products
    const fetchProducts = async () => {
        const { data } = await axios.get('/api/products')
        setProducts(data)
    }
    // Retrieve all products at reload
    useEffect(()=>{
        fetchProducts()
    },[])`

This is a simple function for retrieving products whenever the home page component loads. So every time it loads it should run fetchProducts(). I understood that an empty array means nothing/no dependency so when the component mounts it will run this function.

The error I receive is "Line 19:7: React Hook useEffect has a missing dependency: 'fetchProduct'. Either include it or remove the dependency array"

I'm new to React and am not really understanding the statement. Why would removing the array or adding the function to the dependency change anything?

Isn't the way it's written doing exactly what I would need it to do?

pancake
  • 198
  • 1
  • 15
  • did you import it from react?? like `import { useEffect } from 'react';` – Kunal Tanwar Sep 06 '21 at 17:48
  • 2
    This answers your question https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook – alvarlagerlof Sep 06 '21 at 17:51
  • Does this answer your question? [How to fix missing dependency warning when using useEffect React Hook](https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook) – Will Jenkins Sep 06 '21 at 18:05
  • Thank you both those links help. From what I can understand, by putting the fetchProduct function written into the useEffect and calling it all within useEffect, it will get rid of the error. However, what I dont fully understand is the explanation esp about the callback function etc. How does putting the fetchProduct into the dependency array make sense? Isn't the array supposed to be "monitoring" what changes and then running said function? So it's monitoring the function? Sorry if I'm not articulating it correctly – pancake Sep 06 '21 at 22:34

2 Answers2

1

That error is telling you that yow fetchProducts function is been used inside yow hook, if you want to fix that you have two choices .

Add it to the brackets of the hook

useEffect(()=>{},[fetchProducts]);

Or created it inside the hook.

useEffect(()=>{
  const fetchProducts () =>{...};
   fetchProducts()

},[]);

The way you have it is considered as a side effect

Ernesto
  • 3,944
  • 1
  • 14
  • 29
0

This Warning is basically an eslinting problem as in the dependency array takes primitive type but eslint does not correctly detect dependencies therefore you can fix this by a disable eslint above the lines where there is warning. If you async logic in use Effect put your fetchProducts inside React.useCallback hook and add fetchProducts to use Effect dependency array

Tushar Mistry
  • 373
  • 1
  • 9