T
T
The_good_game2021-04-22 08:00:45
React
The_good_game, 2021-04-22 08:00:45

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

1 answer(s)
B
beem7, 2021-04-22
@The_good_game

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

At the same time, in this case, "taskArray and newArray are NOT essentially the same array" . spread creates a new array.
And then remove this crap somewhere far away from React: Otherwise, in React they beat you for this. Even if the selector was normal, not by tag.
document.querySelector('input').value

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question