pancake
pancake

Reputation: 315

useEffect missing dependency error for simple function

// 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?

Upvotes: 1

Views: 116

Answers (2)

Ernesto
Ernesto

Reputation: 4272

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

Upvotes: 1

Tushar Mistry
Tushar Mistry

Reputation: 392

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

Upvotes: 0

Related Questions