The following code is updating a grid:
useEffect(() => {
const { start_row, start_col, end_row, end_col } = FIXED_COORDINATES;
if (visualize) {
let path = dfs(grid, `${start_row},${start_col}`, `${end_row},${end_col}`);
path = path.map(coord => coord.split(",").map(x => parseInt(x)))
path.forEach(cell => {
setGrid(makeRoute(grid, cell[0], cell[1]));
});
console.log(grid);
}
}, [visualize])
The makeRoute
function is updating a particular cell in the grid:
export const makeRoute = (grid, row, col) => {
// Takes the grid and coordinates of a cell and toggles the route property of that cell
// Returns the modified grid
let newGrid, newRow, newObj;
newObj = {...grid[row][col]}; // gets the cell object
newObj.route = true; // modifies the cell object
newRow = [...grid[row]]; // gets the row in which the above object resides
newRow[col] = newObj; // modifies the row
newGrid = [...grid] // gets the entire grid
newGrid[row] = newRow // modifies the grid
return newGrid;
}
So I'm taking the grid, modifying and returning a new grid which I'm trying to save in state with setGrid
function within useEffect. However, the value doesn't persist in the state. How can I fix this?