Tui
Tui

Reputation: 185

Redux: for loops worked in a reducer but filter didn't

I'm learning Redux and I came across this problem when using import { createSlice } from "@reduxjs/toolkit"

The goal was to remove some objects inside an array that has listId === action.payload.id

This (1) works:

    todosRemoved: (todos, action) => {
      for (let i = todos.length - 1; i > -1; i--) {
        if (todos[i].listId === action.payload.id) {
          todos.splice(i, 1);
        }
      }
    }

but this (2) didn't:

    todosRemoved: (todos, action) => {
      todos.filter((todo) => todo.listId !== action.payload.id)
    }

I'd prefer to use the (2) but I don't know what I did wrong there. I really appreciate if someone could elaborate it. Thanks!

Upvotes: 0

Views: 586

Answers (3)

Sanoodia
Sanoodia

Reputation: 905

todos.filter((todo) => todo.listId !== action.payload.id)

this line is returning your valid objects of array, not updating your actual array. All you have to do is to save these all object in dummy array like this

case SET_TODO:
let dummyArray = todos.filter((todo) => todo.listId !== action.payload.id);
console.log(dummyArray) 
return Object.assign({}, state, {
             todo: dummyArray
        });

Upvotes: 1

vineeth pappu
vineeth pappu

Reputation: 542

Just return the filtered array.

todosRemoved: (todos, action) => {
      return todos.filter((todo) => todo.listId !== action.payload.id) 
}

or even better like..

todosRemoved: (todos, action) => todos.filter((todo) => todo.listId !== action.payload.id)

Upvotes: 1

theonly1me
theonly1me

Reputation: 1248

Array.prototype.filter( ) does not mutate the original array, it instead returns a new array with the values satisfying the filter condition:

So what you need to do is:

todosRemoved: (todos, action) => {
      const newTodos = todos.filter((todo) => todo.listId !== action.payload.id)
      console.log(newTodos); //this will have the expected values
    }

Try running the below snippet example if you want to see an example:

const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13];

const arr1 = arr.filter(el => el % 2 === 0);

console.log('This is the original array (Still Intact):', arr);
console.log('This is the new array:', arr1);

Upvotes: 1

Related Questions