1

I have this warning in my ProductUpdate.js file.

My code looks like this:

 const fetchProduct = () => {
      getProduct(slug)
      .then(p => setValues({...values, ...p.data }))
    }
 
    useEffect(() => {
      fetchProduct()
      fetchCategories()
    }, [])

The warning says:

React Hook useEffect has a missing dependency: 'fetchProduct'. Either include it or remove the dependency array

But when I add fetchProduct to dependency array I enter infinite loop.

I have tried useCallback hook:

 const fetchProduct = useCallback(() => {
      getProduct(slug)
      .then(p => setValues({...values, ...p.data }))
    }, []) 
 
    useEffect(() => {
      fetchProduct()
      fetchCategories()
    }, [fetchProduct])

But then the warning says to add slug and values dependencies to useCallback. When I do I enter infinite loop again.

Any solution?

Rokus
  • 21
  • 5

1 Answers1

1

Adding getProduct, slug, and setValues to the callback dependency array should work:

const fetchProduct = useCallback(() => {
    getProduct(slug)
        .then(p => setValues(values => ({ ...values, ...p.data })))
}, [getProduct, slug, setValues])

useEffect(() => {
    fetchProduct()
    fetchCategories()
}, [fetchProduct, fetchCategories])

Follow the same pattern for putting fetchCategories in a useCallback.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I still get this warning : React Hook useCallback has a missing dependency: 'values'. Either include it or remove the dependency array. You can also do a functional update 'setValues(v => ...)' if you only need 'values' in the 'setValues' call react-hooks/exhaustive-deps – Rokus Mar 20 '21 at 14:31
  • 1
    Are you sure you're using the code in my answer? `values` is the `setValues` parameter, not the outer variable. `.then(p => setValues(values => ({ ...values, ...p.data })))` Try copying my code exactly. – CertainPerformance Mar 20 '21 at 14:32
  • Ok, now it works fine, no warnings, no infinite loops, big thx – Rokus Mar 20 '21 at 14:46
  • When an answer solves your problem, you may consider upvoting and/or marking it as Accepted (check the checkbox on the left) to indicate that the issue is resolved :) – CertainPerformance Mar 20 '21 at 14:47