Reputation: 13
I have one issue with my code where I need to filter though "id" and this is the error that I get " React Hook useEffect has missing dependencies: 'data' and 'filterData'. Either include them or remove the dependency array.
useEffect(() => {
if (content === "") {
setFilterData(data);
return;
}
const filteredData = filterData.filter((item) => item.Id === content);
setFilterData(filteredData);
}, [content]);
Upvotes: 1
Views: 86
Reputation: 2121
You need to add the dependency for data
and filterData
useEffect(() => {
if (content === "") {
setFilterData(data);
return;
}
const filteredData = filterData.filter((item) => item.Id === content);
setFilterData(filteredData);
}, [content, filterData, data]);
You can use the below code. This is the better implementation.
useEffect(() => {
if(data){
const filteredData = content === "" ? data : data.filter((item) => item.Id === content);
setFilterData(filteredData);
}
}, [content, data]);
Upvotes: 2
Reputation: 2412
You only declared content
as dependency in your useEffect
block, but you're actually using data
(which is a prop) and filterData
(which is coming from useState()
) as well.
These are dependencies and the error message is saying you need to declare them too (meaning your useEffect
block will be executed every time one of its dependencies changes) or to remove depencencies at all (meaning your useEffect
block will be executed only once):
useEffect(() => {
if (content === "") {
setFilterData(data);
return;
}
const filteredData = filterData.filter((item) => item.Id === content);
setFilterData(filteredData);
},
[content, data, filterData] // or [] for no depencencies
);
Upvotes: 1