Home > front end >  Remove a todo from the list by index using filter function (Redux react)
Remove a todo from the list by index using filter function (Redux react)

Time:09-22

I'm trying to getting familiarity with Redux trying tio build a simple todo list. I'm struggling to understand why with this code I can't remove a single todo from the list. I would like to use the index instead of the usual id for each todo. This is what I have done so far:

export const saveTodo = createSlice({
    name: 'manageList',
    initialState,
    reducers: {
        addTodoToList: (state, action) => {
            state.todoList.push(action.payload)
        },
        removeTodoToList: (state, action) => {
            state.todoList.filter((todo, index) => index !== action.payload)
        }
    }
})

And this is inside the List component where I dispatch the reducer:

  <div className='list'>
                {todoList?.map((todo, index) => {
                    return <h1 key={index}>{todo}<span onClick={() => dispatch(removeTodoToList(index))}>x</span></h1>
                })}
            </div>

Why this approach doesn't work? Considered the usage of the redux toolkit, Shall I use mutability functions like splice instead? Assigning an id to the todo, would have make it a better choice to filter it? thanks

CodePudding user response:

Filter creates a new array as per documentation here

What this means is that state.todoList.filter((todo, index) => index !== action.payload) is filtering and creating a new array, its just not being assigned to your state.

So you can do either of the following:

// example 1
state.todoList = state.todoList.filter((todo, index) => index !== action.payload)

// example 2
return {
 ...state,
 todoList: state.todoList.filter((todo, index) => index !== action.payload)
}

Considered the usage of the redux toolkit, Shall I use mutability functions like splice instead? Assigning an id to the todo, would have make it a better choice to filter it? thanks

This is down to preference. Since I'm from prehistoric times (pre toolkit/immer), I would prefer using syntax that doesn't mutate state. But as a general recommendation, just use whatever you're comfortable with and stick with it.

One thing to note though is that syntax that doesn't mutate state is better for backwards compatibility; so if you use it a lot you will be better prepared if you ever have to refactor/maintain redux code that doesn't use toolkit or immer.

  • Related