0

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

1 Answer 1

3

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]};
    });
  };
Sign up to request clarification or add additional context in comments.

2 Comments

@bohkovsl thanks that fixed that. but shouldn't arrow function return automatically?
If arrow function has "concise" body (without brackets {}), it returns automatically. But because "block" body was used, you need to explicitly return. Even more, "consice" body will return array, but you must return appropriate key-value object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.