Answer the question
In order to leave comments, you need to log in
Why are the elements in the array duplicated when using setState?
Good afternoon, I can't understand why when adding new elements to the taskArray array, after pressing the button, they are duplicated?
When the user types "Hello", the expected change to the taskArray is ["Hello"], ["Hello", "Hello"] is output instead. Perhaps the point is that taskArray and newArray are essentially the same array, but it's still not clear where a copy of the element added to the array comes from.
class App extends React.Component {
constructor(props) {
super(props)
this.state = {taskArray: []}
}
clickHandler() {
const inputVal = document.querySelector('input').value;
this.setState((prevState, prevProp) => {
let newArray = prevState.taskArray;
newArray.push(inputVal);
return {taskArray: newArray}
})
}
render() {
return (
<div className="App">
<input placeholder="Enter a task"></input>
<button
onClick={() => {
this.clickHandler();
console.log(this.state.taskArray)
}}>
Add task
</button>
</div>
)
}
}
Answer the question
In order to leave comments, you need to log in
Well clickHandler how many times is called - 2 or 1?
If 1 then the problem is with your setState. And you have some kind of exotic one ... I don’t know why this is necessary.
I would do so
this.setState({ taskArray: [...this.state.taskArray, inputVal] });
document.querySelector('input').value
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question