Reputation: 21
React Hook useEffect has a missing dependency: 'init'. Either include it or remove the dependency array react-hooks/exhaustive-deps
src/admin/apiAdmin.js
export const getCategories = () => {
return fetch(`${API}/categories`, {
method: 'GET'
})
.then(response => {
return response.json()
})
.catch(err => console.log(err))
}
src/AddProduct.js
//load categories and set form data
const init = () => {
getCategories().then(data => {
if (data.error) {
setValues({ ...values, error: data.error })
} else {
// console.log(data)
setValues({
...values,
categories: data.data,
formData: new FormData()
})
}
})
}
useEffect(() => {
init();
}, [])
Upvotes: 1
Views: 551
Reputation: 326
Use the useCallback hook to memoize the callback, it'll store the function in memory and only recompute it if its dependencies change [values]
// import { useCallback } from "react";
//load categories and set form data
const init = useCallback(() => {
getCategories().then(data => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
// console.log(data)
setValues({
...values,
categories: data.data,
formData: new FormData()
});
}
});
}, [values]);
useEffect(() => {
init();
}, [init]);
Hope it helped
Upvotes: 5
Reputation: 1316
It's warning you because your init
function is using the values
variable which may change. You can avoid this message by setting your state with a callback that is giving you the previous state.
const init = () => {
getCategories().then(data => {
if (data.error) {
setValues(prev => ({ ...prev, error: data.error }));
} else {
// console.log(data)
setValues(prev => ({
...prev,
categories: data.data,
formData: new FormData()
}));
}
});
};
Upvotes: 2