2

In React i have a function called addOrder that adds object with parameter values to state called data. When i try to console.log(this.state.data) i get an empty array for some reason. When i click button that calls addOrder function again i get array that contains objects with parameter values. Why doesn't console.log show me array values the first time i click button?

import React, { Component } from 'react';



class App extends Component {
  constructor(){
    super()
    this.state = {
      data:[]
    }

  }


addOrder(parameter1, parameter2, parameter3){
  this.setState({
    data:this.state.data.concat(
        {
         one:parameter1,
         two:parameter2,
         three:parameter3
        }
     )          
  });

  console.log(this.state.data);
}


  render() {

    return (
      <div>
            <button onClick={() => this.addOrder('1','2','3')}>ok</button>
      </div>
    )
  }
}

export default App;

I expected console.log to show [{one: "1", two: "2", three: "3"}], but instead i got empty array []

3 Answers 3

3

Call to setState() is asynchronous So javascript compiler does not wait for setState to finish. So it reaches the next line and print your console.log statement and since at this point of time your state is not updated and the data array is empty it prints the empty array to the console.

setState() also comes with a callback which executes when you state has been updated.

You can try this

this.setState({
data:this.state.data.concat(
    {
     one:parameter1,
     two:parameter2,
     three:parameter3
    }
 )          
}, () => console.log(this.state.data));

Will work fine now

Sign up to request clarification or add additional context in comments.

Comments

0
addOrder(parameter1, parameter2, parameter3){
 this.setState({
  data:this.state.data.concat(
    {
     one:parameter1,
     two:parameter2,
     three:parameter3
    }
   )          
  },()=>console.log(this.state.data));
 }

try this way

Comments

0

setState is an asynchronous function. The second argument of setState is a callback so you can use it to know when the function has finished.

Comments

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.