1

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.

2 Answers 2

1

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.

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

2 Comments

I used callback function for setState. I was attempting to provide state value as a parameter to a function then instead I just called the function in the callback of setState, which worked. Thanks.
You are welcome :) if it does provide the answer to your question than feel free to accept it as the correct answer. Best regards.
1

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.

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.