Answer the question
In order to leave comments, you need to log in
How correct is this implementation of adding and removing elements?
The example has two methods: adding and removing an element from an array. In React, you can't change state directly.
In order to add an element to an array using the push method, I need to create a copy of the array because the push method is mutable.
To remove an element, I used the splice method. It's immutable, so you don't need to make a copy of the array, but since this.state.items is repeated more than once, it's not a bad idea to destructure. Why does removeItem work as a method, but addItem only as an arrow function? Me interests how correctly I implemented these two methods.
Answer the question
In order to leave comments, you need to log in
So you seem to be aware that the state should not be changed directly - but nevertheless you do it.
What do you mean by "mutable" and "immutable" in relation to array methods, I don't know, and I don't want to know. But I can say for sure - not what you need. You should definitely take a look here .
Make a copy of the array before splice, and splice itself on the copy - just like push when adding an element.
By the way, about the addition - why do you have a constant in the method code as a new id? Clicked "add" twice - here are two elements with the same id. Was it really that hard to generate a unique one? For example .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question