Im just starting with react and I get a weird behaviour that I am not able to understand.
class App extends Component {
state = {
newTask: [
{
header: 'Header',
description: 'Detailed description'
}]}
setTask = () => {
console.log(this.state.newTask)
this.setState({newTask: [
{
header: "some change",
description: "some change again"
}]});
console.log(this.state.newTask)}
render() {
return (
<div className="App">
<h1>Hello There.</h1>
<NewTaskModal callbackFromParent={this.setTask}/>
<Tasks task={this.state.newTask} />
</div>
);}}
export default App;
The App component is a parent to other component Tasks which is a parent to component Task. When I click button in NewTaskModal component, the setTask
method is called and it should update the state. I have put console.logs around the block of code responsible for updating the state to see its current value.
Clicking the button for the first time console.logs in both cases the initialized value of the state BUT in Tasks component the Task is rendered with the new values ('some change'). After the clicking the button for the second time it then finally updates the state and console.logs the updated values.
My desired result is updating the state by not changing it but by adding more Objects of header and description to it. Also I would like to after clicking the button for the first time to update the state immediately not after the second click.
I have spent hours on this and I cant seem to find the right solution so I ask for help..
Thank you.