rio
rio

Reputation: 807

Rendering React app does not apply when adding items to an array inside a state

I'm truing to make a todo-app for practicing. For some reason when I press the add button nothing happen, but then if I apply "onChange" on the input field the created todo does display in the todos list. I've been trying to find a solution for that for the last few hours, I believe I missed something... hope someone could figure it out !

App.js

class App extends Component {
  state = {
    newTask: { id: 0, task: "" },
    tasks: [
      { id: 1, task: "task1" },
      { id: 2, task: "task2" },
      { id: 3, task: "task3" }
    ]
  };

  newTask = e => {
    this.setState({
      newTask: { id: this.state.tasks.length + 1, task: e.target.value }
    });
  };

  addTask = e => {
    this.setState(prevState => {
      prevState.tasks.push(this.state.newTask);
    });
  };

  render() {
    return (
      <div className="App">
        <Header title="Todo List" />
        <Form input={this.newTask} add={this.addTask} />
        <ul>
          {this.state.tasks.map(t => (
            <Tasks task={t.task} key={t.id} />
          ))}
        </ul>
      </div>
    );
  }
}

export default App;

const form = props => {
  return (
    <div>
      <input
        type="text"
        placeholder="Type your task here..."
        onChange={props.input}
      />
      <button onClick={props.add}>Add</button>
    </div>
  );
};

const tasks = props => {
  return <div>{props.task}</div>;
};

Upvotes: 0

Views: 41

Answers (1)

bohkoval
bohkoval

Reputation: 375

You doesn't return anything inside setState function in addTask. Therefore you actually update state, but do not trigger react update lifecycle.

I suppose you to try smth like this:

addTask = e => {
    this.setState(prevState => {
        return { tasks: [...prevState.tasks, this.state.newTask]};
    });
  };

Upvotes: 3

Related Questions