Home > Net >  Cannot update a component while rendering a different component .To locate the bad setState() call i
Cannot update a component while rendering a different component .To locate the bad setState() call i

Time:08-22

Learning react by coding, i'm having this error and it is because 'dispatch(clearAnalyserData());' which is inside 'setFilteredGraphData', in the same useEffect i'm using 'clearAnalyserData' two times but that second one is working fine and not giving error. What am i doing wrong, is there some rule on not to dispatch inside 'setFilteredGraphData' ?

Warning: Cannot update a component (ConnectedNavBar) while rendering a different component (ConnectedGraphs). To locate the bad setState() call inside ConnectedGraphs, follow the stack trace as described in

import {
  clearAnalyserData,
} from "../../redux/actions";


  const [filteredGraph, setFilteredGraph] = useState("");

useEffect(() => {
    if (currentCam) {
    
      const filterCamera = () => {
       
        setFilteredGraph(
          _.isEqual(filteredGraph, { links: links, nodes: allNodes })
            ? () => {
                dispatch(clearAnalyserData());

                setGraphData("");

                return visualGraph.model;
              }
            : { links: links, nodes: allNodes }
        );

        dispatch(clearAnalyserData());
      };
    filterCamera() ;
    } else {
    ....
    }
  }, [currentCam]);

CodePudding user response:

Changing other states in one state's update function can lead to errors like this.

Removing some spaghetti should fix the issue:

const filterCamera = () => {
  if (_.isEqual(filteredGraph, { links: links, nodes: allNodes })) {
    setGraphData("");
    setFilteredGraph(visualGraph.model)
  } else {
    setFilteredGraph({ links: links, nodes: allNodes })
  }
  dispatch(clearAnalyserData());
};

CodePudding user response:

When state is updated using its previous value the callback argument of the state setter should be used, as state updates may be asynchronous.

In a class component filterCamera could be written as follows:

filterCamera=()=> { 
    this.setState((state)=> {
        var equal = _.isEqual(filteredGraph, { links: links, nodes: allNodes });
        if(equal) { // can be rewritten using ternary operator
            return {graphData:'', filteredGraph: visualGraph.model };
        } else {
            return {filteredGraph: {links, nodes: allNodes}};
        }
    })
    dispatch(clearAnalyserData());
};

In class components, the problem of updating a state property inside another state property does not occur.

  • Related