2

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

3
  • Is the initialState an array of todos ? Commented Aug 20, 2018 at 8:46
  • No, the initialState is an empty array. Commented Aug 20, 2018 at 8:48
  • ok so the @Pavel answer is correct Commented Aug 20, 2018 at 8:54

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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)]

2 Comments

You don't need to use spread operator since Array.prototype.filter method returns new array. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
The above is useful when you have to maintain the empty array after filtering/eliminating the last item.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.