Reputation: 157
I have two components that talk to each other. In component A I have a list of locations and whenever a user clicks on one of the locations in this component this filters a list of properties in component B dependent on the clicked location. This works, so far so good. But in component B I use a useEffect hook to check for the selectedLocation variable that comes to it via props from component A so I can update the state. And in this useEffect() call VS Code complains that "React useEffect Hook has a missing dependency "...dataState". But of course I can't put the dataState in to the dependency array because it would cause an infinite loop. And by the way, dateState is managed via a useState Hook. Here is my useEffect hook:
// If there is a new selected location from the treeview, update the grid state
useEffect(() => {
const newState: State = {
...dataState,
filter: {
logic: 'and',
filters: [
{
field: 'location',
operator: 'contains',
value: selectedLocation,
},
],
},
};
setDataState(newState);
}, [selectedLocation]);
Any help would be appreciated.
Upvotes: 0
Views: 298
Reputation: 2486
Actually, "...dataState"
isn't define in your B component. so it's showing missing dependency you needed a reference for this like this:
useEffect(() => {
setDataState(dataState=> ({...dataState, filter: {
logic: 'and',
filters: [
{
field: 'location',
operator: 'contains',
value: selectedLocation,
},
],
},
}));
}, [selectedLocation]);
Upvotes: 1
Reputation: 80
You can also do by creating another state like
const [newDataState,setNewDataState]=useState();
useEffect(() => {
const newState: State = {
...dataState,
filter: {
logic: 'and',
filters: [
{
field: 'location',
operator: 'contains',
value: selectedLocation,
},
],
},
};
setNewDataState(newState);
}, [selectedLocation,datastate]
);
now use newDataState as dependency in second useEffect and set state of your original state.
useEffect=()=>{
setDataState(newDataState);
},[newDataState]
Upvotes: 1
Reputation: 671
Try to set dataState
like that:
useEffect(() => {
setDataState(oldDataState => ({
...oldDataState ,
filter: {
logic: 'and',
filters: [
{
field: 'location',
operator: 'contains',
value: selectedLocation,
},
],
},
}));
}, [selectedLocation]);
This way it would be considered as a parameter
instead of a dependency.
Upvotes: 2