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.
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.
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.
This went from "I get this" to "What in h is he talking about"?
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
})
}
The lesson is for removeTodos, but the test is for addTodos. modification left as an exercise for the reader?
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) })
Yikes... sorry about that formatting D:
Is it really necessary to have
evt.preventDefault()
forhandleRemove
?
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.