0

this is my first post and I am creating my first react app which is a path finding web application. The goal is given a start block, traverse the maze using BFS method until it reaches the end block.

UI with Start/End/Walls

UI with Start/End/Walls

I have a state array to keep track of visited cells.

const [visitedCells , setVisitedCells] = useState([]);

What I did was first append the starting node ( in green) to a local queue. Then run a while loop to check if the queue is empty. If the queue is not empty, pop the element and add the popped element to the visitedCells state array and queue its children nodes.

  addToVisitedCells(startCell);
  let neighbourQueue = [];
  neighbourQueue.push(startCell);

  while(neighbourQueue.length > 0){
      console.log("Queue has items");
      var cellIdParent = neighbourQueue.pop();

      //Additional code omitted as not useful 

      if(isCellInBoard(rowAbove,colPos) && !isCellAlreadyVisited(childTopId) && !isInWallArray(childTopId)){
          neighbourQueue.push(childTopId);
          addToVisitedCells(childTopId);

          if(childTopId === endCell)
              return;
      }

      //Additional code for left,right and bottom neighbors

And here is the function addToVisitedCells where I add the current cell to visitedCells if it has not been visited before.

const addToVisitedCells = (cellId) => {
  if(!isCellAlreadyVisited(cellId)){
      setVisitedCells(previousState => (
          [...previousState, cellId]
      ));
  };
};

The problem is that the state array update is too slow. From what I understand, react batches state updates. But because the visitedCells array is never updated on time whilst the while loop runs, it ends up being in an infinite loop as my neighbor nodes are never updated in the visitedCells state. Therefore my queue will just keep popping and pushing the same neighbor nodes over and over again.

What can I do to ensure the state updates on time? Or should I be using another hook instead?

swl
  • 1
  • 2
  • check out this link: https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately?rq=1 – sloont Jun 19 '21 at 14:24

0 Answers0