Reputation: 21
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?
Upvotes: 1
Views: 768
Reputation: 371198
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
.
Upvotes: 1