1. 15
    Remove Items from a List without Mutations
    5m 31s

Remove Items from a List without Mutations

Andy Van Slaars
InstructorAndy Van Slaars

Share this video with your friends

Send Tweet

In this lesson, we’ll add the ability to remove items from our list. We’ll add some css to show a delete link while hovered over an item and handle a click event from the component to remove the corresponding item from the list by its id.

Witold Adamus
Witold Adamus
~ 4 years ago

Hey, why haven't you implemented removal with a shorter form using arrays filter? Eg. removeItem = (items, id) => items.filter(item => item.id !== id) I know that this version will remove all (many) items with a given id (function from a video will remove just 1st object with this id), but id should be unique anyway.

Andy Van Slaars
Andy Van Slaarsinstructor
~ 4 years ago

Witold,

Filter is a perfectly valid approach here. I did it this way here to show a different approach and to remain consistent with the syntax in the other lessons.

AJ
AJ
~ 4 years ago

This went from "I get this" to "What in h is he talking about"?

Juan Marco
Juan Marco
~ 3 years ago

Is it really necessary to have evt.preventDefault() for handleRemove? Mine is written like this and seems to be working just fine:

handleRemove = (id) => {
  const updatedTodos = removeTodo(this.state.todos, id)
  this.setState({
    todos: updatedTodos
  })
}
Ken
Ken
~ 3 years ago

The lesson is for removeTodos, but the test is for addTodos. modification left as an exercise for the reader?

Dan LaFreniere
Dan LaFreniere
~ 2 years ago

The lesson is for removeTodos, but the test is for addTodos. modification left as an exercise for the reader?

You can find this code at the top of the transcript in the code section: test('removeTodo should remove an item by id', () => { const startTodos = [ {id:1, name: 'one', isComplete: false}, {id:2, name: 'two', isComplete: false}, {id:3, name: 'three', isComplete: false} ] const targetId = 2 const expectedTodos = [ {id:1, name: 'one', isComplete: false}, {id:3, name: 'three', isComplete: false} ] const result = removeTodo(startTodos, targetId)

expect(result).toEqual(expectedTodos) })

test('removeTodo should not mutate the original array', () => { const startTodos = [ {id:1, name: 'one', isComplete: false}, {id:2, name: 'two', isComplete: false}, {id:3, name: 'three', isComplete: false} ] const targetId = 2 const result = removeTodo(startTodos, targetId)

expect(result).not.toBe(startTodos) })

Dan LaFreniere
Dan LaFreniere
~ 2 years ago

Yikes... sorry about that formatting D:

Steeve
Steeve
~ 2 years ago

Is it really necessary to have evt.preventDefault() for handleRemove?

Yes and no. If you do not prevent the event to bubble, your location will update with a trailing # and scroll to the top of the page. It might not be visible in a small test but imagine this component being further down on the page.