Home > Mobile >  React useEffect Hook complains about missing dependency
React useEffect Hook complains about missing dependency

Time:11-05

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.

CodePudding user response:

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.

CodePudding user response:

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]);

CodePudding user response:

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]
  • Related