1

New to React.js, I am having hard time using the spread operator in my reducers to update my state that has an 2D-array property.

For instance initial state is so:

let initialState = {
    grid: new Array(5).fill(new Array(5).fill(0)),
    player: { coords: [2,3], health: 100 }
}

After binding the action, lets say the payload goes to PRESS_LEFT

case PRESS_LEFT: {
  let oldCoords = [state.player.coords[0], state.player.coords[1]];
  let newCoords = [state.player.coords[0], state.player.coords[1]-1];
  let thereIsWall = validateWall(state.grid, newCoords);
  if (thereIsWall){
    return state
  } else{
    return{
      ...state,
      player: { ...state.player, coords: newCoords },
      grid: { ...state.grid, state.grid[oldCoords[0]][oldCoords[1]] = 1 }
    }
  }
}

I am able to update the player's state, but not the grid. Essentially I want to update the coordinates from oldCoords and assign it to 1.

1 Answer 1

1

its because the old value is assigned to null

let initialState = { grid: new Array(5).fill(new Array(5).fill(0)), player: { coords: null, health: 100 } }

and then you are trying to read zeroth index of null, that will throw the error.

let oldCoords = [state.player.coords[0], state.player.coords[1]];

Update:

grid is an array but you are returning the object ..change to below syntax

grid: [ ...state.grid, state.grid[oldCoords[0]][oldCoords[1]]=1 ]   
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, I forgot edit my post where players.coords is already initialized when action is dispatched.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.