Ad

Modify A SetState From The Data Retrieved Via A Link

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 :)

Ad

Answer

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));
Ad
source: stackoverflow.com
Ad