Reputation: 13422
In my application state I have a teams array.
This teams array contains team information, and an array of players.
The players and teams are decoupled on the server and joined together when the app calls /teams
.
I update the state with the response.
Now when I delete a player, I update the server. Then the response gives me a team id and player id.
My case statement
case DELETE_PLAYER_SUCCESS:
// Copy the state
const playerDeleteSuccessTeams = [...state.teams];
// Find the team and remove the player
playerDeleteSuccessTeams.forEach((team, index) => {
if (team._id === action.result.tid) {
playerDeleteSuccessTeams[index].playersData.splice(0, action.result.index);
}
});
return {
...state,
teams: playerDeleteSuccessTeams
};
Is this a flawed approach?
Upvotes: 0
Views: 789
Reputation: 191976
You should create a new object / array for everything that changed because of the deletion, if you want React components to react to the change.
I'll use the ids, and not the index, because you wrote in the description:
Then the response gives me a team id and player id
I'm guessing the state of the shape, and the action data, so you'll have to adjust this to fit your code:
case DELETE_PLAYER_SUCCESS:
const { tid, pid } = action.result; // tid - team id, pid - player id
// create a new teams array by mapping the old teams
const teams = state.teams.map((team) => team._id !== tid ? team : ({ // when the tid is found, return a new team object
...team,
playersData: team.playersData.filter((player) => player._id !== pid) // create a new array using filter to remove the player with the pid
}));
return {
...state,
teams // assign the new teams array to the state
};
Upvotes: 2