0

Hello everybody

I'm a young beginner in programmtion. I'm trying to recover data from a Link to another component. Everything works except just put this recovered data in a state object with setState. I think I don't know evrything possible about setState but I'm quite lost.

I have this link which send the data "Command_ID" :


<Link to={`/produits/${Command_ID}`} className="item" params={{ Command_ID: {Command_ID}}}>

And as expected, I recover data like this and I recall it "order_id" :


state = {orderId: null};

     componentDidMount() {
        const  order_id  = this.props.match.params;


        console.log(order_id);
        this.setState({orderID: order_id});
        console.log(this.state.orderID);
    }

I can see in my console.log(order_id) the right number recover in the link part with the good "Command_ID". But when I try to put it with the setState and see in my console if it works, I just have a value of undefined for this.state.orderID

Thank you for your help :)

  • undefined or null ? – Ali Faris Jun 26 '19 at 13:04
  • 1
    `setState` is asynchronous. The code you have does what you want it to, but the second console.log command runs too early to show the change. You can put it in a callback though: `this.setState({ orderID: order_id }, function () { console.log(this.state.orderID); });` (the function will run after the state has changed) –  Jun 26 '19 at 13:04
  • undefined. Okay so you think I have to let a moment before to verify this value ? because it's the first time I had this problem – Julien Txerriak Guillou Jun 26 '19 at 13:08
  • 1
    It's not that we "think" this, it's definitely what's happening. https://reactjs.org/docs/react-component.html#setstate quote: `setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.` –  Jun 26 '19 at 13:12

1 Answers1

1

setState is async method , to execute something after the state is set you can pass function as second parameter for setState

this.setState({orderID: order_id}, () => console.log(this.state.orderId));
Ali Faris
  • 17,754
  • 10
  • 45
  • 70