escapee
escapee

Reputation: 423

How to use setState from .then in another function as a parameter in ReactJS

I am new to ReactJS. I have:

this.service
        .getData({})
        .then((response: any) => {
            this.setState({
                id: response.id
            });
        })

getStats(this.state.id) {
...
}

I am not able to get the value for id outside .then. I want to use id in multiple functions. How do I get the value in state so that I don't have to call the function several times? Please suggest.

Upvotes: 1

Views: 282

Answers (2)

buzatto
buzatto

Reputation: 10382

on class base components, given the async nature of state update you use more often componentDidUpdate lifecycle. this lifecycle provides prevProps, prevState, snapshot as arguments, which are usefull to you do some validation with current state before triggering your actions.

fwiw, this.setState can receive a function as second parameter also. that function will be executed once state is updated, enabling you to have access to the most current state.

Upvotes: 1

Sharath M.H
Sharath M.H

Reputation: 83

Once the state is updated, it will call the render method again. In the next render call you will have the state updated. Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState.

So in order to use the state after the state is set, either you can use some effects or component life cycle to get the updated state.

Upvotes: 1

Related Questions