A
A
Alexey Milyutin2019-05-21 15:01:09
JavaScript
Alexey Milyutin, 2019-05-21 15:01:09

Why is the array set to null when updating state?

Good afternoon, I can not understand in any way for what reason the null value is written to the array?
I write any words and numbers to the input, it still gives out that the value of the array is null

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todoValue: ['london']
    };
  }
  render() {
    return (
      <div className="body-container">
        <h1>To Do List</h1>
        <input type="text" onKeyDown={this.handleSubmit}/>
        <ul>
          {this.state.todoValue.map(item => (
            <Li text={item}/>
          ))}
        </ul>
      </div>
    )
  }
  
  handleSubmit = (e) => {
    if (e.keyCode === 13) {
      console.log('success');
      this.setState(prevState => ({
        todoValue: [...prevState.todoValue, e.target.value]
      }));
      e.target.value = '';
    }
  }
}

5ce3eb75ce026195388241.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-05-21
@doppelgangerz

Your array is not equal to null, but at the time of calling the callback passed to setState, SyntheticEvent ceases to exist.
You have two options:
1. Write the value of e.target.value to a variable and pass the variable to the callback:

handleSubmit = e => {
  if (e.keyCode === 13) {
    const { value } = e.target;

    this.setState(prevState => ({
      todoValue: [...prevState.todoValue, value],
    }));
    e.target.value = '';
  }
};

2. Use event.persist(), but then you need to change the value of e.target.value in the setState callback, otherwise you will overwrite the value before saving it in state:
handleSubmit = e => {
  if (e.keyCode === 13) {
    e.persist();

    this.setState(
      prevState => ({
        todoValue: [...prevState.todoValue, e.target.value],
      }),
      () => {
        e.target.value = "";
      }
    );
  }
};

I would use the first option.
Similarly, you must use the key property on lists:
{this.state.todoValue.map((item, index) => (
  <Li key={index} text={item} />
 ))}

Lists and keys

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question