I'm building my first application with React and Redux. I'm trying to delete an item from an array in my reducer using splice.
Here my state:
favourite: { recipes: [], wines: [], products: [] }
Here my action:
if (action.type === "REMOVE_RECIPE_FROM_FAV") {
let favourite = state.favourite;
favourite.recipes.splice(action.data, 1);
return {
...state,
favourite: favourite,
};
}
When i console.log favourite i can see that I'm deleting the item, but my component doesn't update.
Could you please help me?
You have to take care of the immutibility of the redux
state. You need to make a copy of the recipes
array and change it and merge with the state without affecting the others.
if (action.type === "REMOVE_RECIPE_FROM_FAV") {
let favourite = state.favourite;
const cloneRecipes = [...favourite.recipes];
cloneRecipes.splice(action.data, 1);
return {
...state,
favourite: {
...state.favourite,
recipes: cloneRecipes
}
}
}
Note that, the [...favourite.recipes]
makes a shallow copy of the recipes
array. For a nested array, it does not help you.
I suggest you to use Immutability Helpers library instead. By using this library the same task could be done like:
if (action.type === "REMOVE_RECIPE_FROM_FAV") {
return update(state, {
favourite: {
recipes: {$splice: [[action.data, 1]]}
}
});
}
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