Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to modify a specific object at a index using spread operator in react-redux?

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 ifActive attribute.

like image 759
Raj Rj Avatar asked Oct 19 '22 02:10

Raj Rj


1 Answers

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;
        }
    }
like image 75
elmeister Avatar answered Oct 20 '22 22:10

elmeister