Once I run the below code, I get the following error:
React Hook useEffect has a missing dependency: 'list'. Either include it or remove the dependency array react-hooks/exhaustive-deps
I cannot find the reason for the warning.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Form from './Form';
const App = () => {
const [term, setTerm] = useState('pizza');
const [list, setList] = useState([]);
const submitSearch = e => {
e.preventDefault();
setTerm(e.target.elements.receiptName.value);
};
useEffect(() => {
(async term => {
const api_url = 'https://www.food2fork.com/api';
const api_key = '<MY API KEY>';
const response = await axios.get(
`${api_url}/search?key=${api_key}&q=${term}&count=5`
);
setList(response.data.recipes);
console.log(list);
})(term);
}, [term]);
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Recipe Search</h1>
</header>
<Form submitSearch={submitSearch} />
{term}
</div>
);
};
export default App;
The warning "React Hook useEffect has a missing dependency" occurs when the useEffect hook makes use of a variable or function that we haven't included in its dependencies array. To solve the error, disable the rule for a line or move the variable inside the useEffect hook.
Empty dependency array So what happens when the dependency array is empty? It simply means that the hook will only trigger once when the component is first rendered. So for example, for useEffect it means the callback will run once at the beginning of the lifecycle of the component and never again.
Missing dependencies are those dependencies that are not available in the repository, so you cannot add them to your deployment set. You can set Deployer to ignore missing dependencies when you create the project (see Creating a Project) or when you check unresolved dependencies.
useEffect(callback, dependencies) is the hook that manages the side-effects in functional components. callback argument is a function to put the side-effect logic. dependencies is a list of dependencies of your side-effect: being props or state values.
Inside your useEffect you are logging list
:
console.log(list);
So you either need to remove the above line, or add list
to the useEffect dependencies at the end.
so change this line
}, [term]);
to
}, [term, list]);
You can disable the lint warning by writing:
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [term]);
You can disable this by inserting a comment
// eslint-disable-next-line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With