0

I'm trying to make a to do list and it works but the items are shown in the array only after a new entry

  addItem = event => {
    event.preventDefault()
    const items = [...this.state.items, this.state.item]
    this.setState({ items, item: '' })
    console.log(this.state)
  }

  render() {
    return (
      <div>
        <form className='form'>
          <input
            onChange={this.handleChange}
            value={this.state.item}
            type="text"
            placeholder='Enter new task' />
          <button type='submit'
            onClick={this.addItem}>OK!</button>
        </form>
        <div className='item-list' >
          {this.renderItems()}
        </div>
      </div>
    )
  }
} 

chrome console

kiko
  • 11
  • 3
    state is updated asynchronously. To log the updated state, pass an optional second argument to `this.state` which is a callback function. This callback is invoked _after_ state has been updated. `this.setState({ items, item: '' }, () => console.log(this.state));` – Yousaf Jan 06 '21 at 14:39
  • Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button). Stack Snippets support React, including JSX; [here's how to do one](http://meta.stackoverflow.com/questions/338537/). We can't help you (other than Yousaf's observation above) without more complete information, I'm afraid. For instance: How are you initializing `this.state`? – T.J. Crowder Jan 06 '21 at 14:41

0 Answers0