Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an element from array using redux

I am trying to make a todo app using redux and I'm stack on how to delete a todo from the array.

reducer.js

export default function todo(state, action) {
switch (action.type) {
  case 'ADD_TODO':
    return [
      ...state,

      {
        id: action.id,
        text: action.text,
        completed: false
      }
  case 'REMOVE_TODO':
    return {
      id: action.id,
      ...state.slice(id, 1)
    }
  default:
    return state;
 }
}

action.js

let nextTodoId = 0
export const addTodo = text => ({
  type: 'ADD_TODO',
  id: nextTodoId++,
  text
})

export const removeTodo = id => {
  type: 'REMOVE_TODO',
  id
}

So far i can add and toggle a todo as completed or not. Thanks

like image 567
PanosCool Avatar asked Aug 04 '26 09:08

PanosCool


2 Answers

Using redux you need to return all array elements except the removed one from reducer.

Personally, I prefer using the filter method of the Array. It'll return you a shallow copy of state array that matches particular condition.

case 'REMOVE_TODO':
return state.filter(({id}) => id !== action.id);
like image 92
Pavlo Kozlov Avatar answered Aug 06 '26 22:08

Pavlo Kozlov


In react redux application, you should know, you always have to create a new object, to deleting an item please use spread operator like this :

return [...state.filter(a=>a.id !== id)]
like image 32
jsDevia Avatar answered Aug 07 '26 00:08

jsDevia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!