Raj Rj Raj Rj - 3 months ago 11
Javascript Question

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.

Answer

The spread operator isn't doing anything special. In this case it's generally used for copying the state to prevent mutating the original object.

You are only modifying the tabs value in this case, so you shouldn't need to spread the entire object. So something like this should be sufficient:

const playerReducer = (state = initialPlayerState , action) => {
    switch (action.type) {
        case SELECT_PLAYER:
          // Update each of the players' `ifActive`, replace the prior `tabs` reference
          state.tabs = state.tabs.map(
              player => {...player, {ifActive: player.id === action.payload}}
          );
          return state;
        default:
          return state;
    }
}