Matt Brody
Matt Brody

Reputation: 1513

Why is my to do list failing to update when state is being updated?

I'm writing a simple to do list app, but the functional component that maps the to-do items in the array is not running again after rendering the initial items and I add another one and I don't' know why.

I can see in the console that the state is being updated with a new item, so I'm just stuck wondering why it's not displaying on the page when I add a new item.

import React from 'react';

class App extends React.Component {
  state = { items: [
    {
      id: 1,
      item: 'code another react app'
    },
    {
      id: 2,
      item: 'eat some cheetos'
    }
  ],
  inputVal: ''
}

  onFormSubmit = (e) => {
    e.preventDefault();
    let newId = Math.random();
    let newItem = this.state.inputVal;
    this.setState({ 
      items: [
        ...this.state.items, 
        {id: newId, item: newItem }
      ], 
      inputVal: ''
    })
  }

  toDoList = this.state.items.map(item => {
    console.log(item)
    return (
      <div key={item.id}>
        <li>{item.item}</li>
      </div>
    )
  })

  render() {
    console.log(this.state)
    return (
      <div>
        <form onSubmit={this.onFormSubmit}>
          <input 
            placeholder="add a to do item" 
            value={this.state.inputVal} 
            type="text" 
            onChange={e => this.setState({ inputVal: e.target.value })}
          />
        </form>
        {this.toDoList}
      </div>
    );
  }
}

export default App;

Upvotes: 0

Views: 39

Answers (1)

kkangil
kkangil

Reputation: 1746

The toDoList variable is set only one time.

you have to use in render method.

render() {
    const toDoList = this.state.items.map(item => {
      console.log(item)
      return (
        <div key={item.id}>
          <li>{item.item}</li>
        </div>
      )
    })
    return (
      <div>
        <form onSubmit={this.onFormSubmit}>
          <input 
            placeholder="add a to do item" 
            value={this.state.inputVal} 
            type="text" 
            onChange={e => this.setState({ inputVal: e.target.value })}
          />
        </form>
        {toDoList}
      </div>
    );
  }

Upvotes: 1

Related Questions