0
votes

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();
    }, [])

My front code Backend code

2
It's a linter error, not an actual error. Ignore it. useEffect(someFn, []); is a perfectly fine way to run a side-effect on mount.Jared Smith

2 Answers

1
votes

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()
      }));
    }
  });
};
4
votes

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