Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using splice in reducer (redux)

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?

like image 658
Davide Avatar asked Oct 19 '25 13:10

Davide


1 Answers

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]]}
        }
    });
}
like image 160
Sajeeb Ahamed Avatar answered Oct 21 '25 02:10

Sajeeb Ahamed