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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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
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.
Ok, now it works fine, no warnings, no infinite loops, big thx
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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.