-2

export default function Home() {

const [products, setProducts] = useState([]);
const [error, setError] = useState(false);

const loadAllProducts = React.useCallback(() => {
    getProducts()
    .then(data => {
        if (data.error) {
            setError(data.error);
            console.log(error);
        } else {
            setProducts(data);
        }
    });
},[]);

useEffect(() => {
    loadAllProducts();
}, [loadAllProducts]);



return(
    <div>
        <h1>Home Component</h1>
        <div className="row">
            {products.map( (product, index) => {
                return(
                    <div key={index}>
                        <h1>{product}.name</h1>
                    </div>
                );
            })}
        </div>
    </div>
);

}

After executing the above codes getting this error React Hook React.useCallback has a missing dependency: 'error'. Either include it or remove the dependency array.

  • 1
    Does this answer your question? [How to fix missing dependency warning when using useEffect React Hook](https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook) – Nick Parsons Oct 05 '21 at 10:38
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 10 '21 at 04:35

1 Answers1

0
export default function Home() {

const [products, setProducts] = useState([]);
const [error, setError] = useState(false);

const loadAllProducts = React.useCallback(() => {
    getProducts()
    .then(data => {
        if (data.error) {
            setError(data.error);
            console.log(error);
        } else {
            setProducts(data);
        }
    });
},[error]);

useEffect(() => {
    loadAllProducts();
}, [loadAllProducts]);

Pass the dependency just like the warning says, but in your case this dependency is a function so it's good to wrap it in a useCallback otherwise you'll get another warning.

kevin
  • 872
  • 5
  • 18