I want to use spread operator. Scenario is that there are no of players (displayed as player tile on UI). Whenever I am clicking on any of player-tile, it is becoming active (getting highlighted). Condition is that at a time only one player should be highlighted. So, when a player-tile is clicked its attribute ifActive: true, and rest of players attribute ifActive: false
The playerReducer is getting clicked player-id as action.payload (action.payload is giving the id of player which is currently clicked). Now I have to modify my state without mutating it. I have to use spread operator for it. how to modify a specific object at a index using spread operator?
const initialPlayerState = {
  tabs: [
    { id: 1, name: 'player 1', ifActive: false },
    { id: 2, name: 'player 2', ifActive: false },
    { id: 3, name: 'player 3', ifActive: false },
  ]
} 
const playerReducer = (state = initialPlayerState , action) => {
    switch (action.type) {
        case SELECT_PLAYER:
          //how to modify state using spread operator, and how to modify 
          //a specific object at a specific index.  
          return { ...state, /*some code hrere*/};
        default:
          return state;
    }
}
how to modify a specific object at a index using spread operator? Strictly, I have to use spread operator and each player should have
ifActiveattribute.
If you need to update one of the players, for example ifActive flag, and recreate the tabs array to trigger re-render of tabs component, you can do it like this
    const initialPlayerState = {
      tabs: [
        { id: 1, name: 'player 1', ifActive: false },
        { id: 2, name: 'player 2', ifActive: false },
        { id: 3, name: 'player 3', ifActive: false },
      ]
    } 
    const playerReducer = (state = initialPlayerState , action) => {
        switch (action.type) {
            case SELECT_PLAYER:
              return { 
                ...state, // If you have something else in your state
                tabs: tabs.map(player => player.ifActive || player.id === action.id ? {
                  ...player,
                  ifActive: player.id === action.id
                } : player)
              };
            default:
              return state;
        }
    }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With