Maramal
Maramal

Reputation: 3466

React Context API does not update state after async call

I was following this example for my own code but the state does not update after an async fetch call when clicking a button.

It is a real simple application, when the user loads the page, it loads also the state in componentDidMount(). When the user clicks the Get "joke" button, it set the state again with a new "joke".

When the page loads, the joke is well rendered after a couple of milliseconds. But when clicking the button it only shows the fetched "joke" in the console but the state is null.

When clicking the button I logged this object and it looks like this, is it correct?

Image

Here is the code and the app "working": https://codesandbox.io/s/friendly-shirley-qupr4

I appreciate any comments.

Upvotes: 0

Views: 1347

Answers (1)

Pio
Pio

Reputation: 123

So you forgot about binding action. In JokeStat.js bind action in

        <JokesContext.Provider
                value={{
                    joke: this.state.joke,
                    getJoke: this.getJoke.bind(this)
                }}
            >
                {this.props.children}
            </JokesContext.Provider>

Or change

    async getJoke() {
        console.log("get joked triggered");
        const joke = await fetchJoke();
        console.log(joke,'joke')
        console.log("state", this.state);
        this.setState({ joke });
    }

to

     getJoke = async() => {
        console.log("get joked triggered");
        const joke = await fetchJoke();
        console.log(joke,'joke')
        console.log("state", this.state);
        this.setState({ joke });
    }

or 3rd option

     <JokesContext.Provider
         value={{
           joke: this.state.joke,
           getJoke: ()=>this.getJoke()
          }}
        >
           {this.props.children}
        </JokesContext.Provider>

Upvotes: 1

Related Questions