Search code examples
javascriptreactjsasync-awaitweb3js

React async / await and setState not rerendering


I have a problem with rerender after getting result from web3 call - execution of smart contract. Code below:

this.setState({ loading: true });

await contractInstance.methods
                .myMethod(params)
                .send({ from: myAccount, gas: 10000000 })
                .then(async function(receipt) {
                    let txHash = receipt.transactionHash;
                    ...

                    // await saveToDb(thHash, ...)

                    this.setState({ dateToDisplay: myVar.publishDate, loading: false });

..

and the render is as below:

render() {
        if (!this.state.loading) {
            return (
            ...
             {this.state.dateToDisplay}

I have other methods where this pattern works, but here I could not make it work. I tried to make setState async and await it, like:

setStateAsync(state) {
        return new Promise(resolve => {
            this.setState(state, resolve);
        });
    }

But does not help either. Any ideas?


Solution

  • Why do you combine await and promises?

    The point of await is to stop the execution at that point and wait for the promise to resolve. The const result = await promise; is a replacement for promise.then(result => ...).

    You could do this:

    const receipt = await contractInstance.methods
        .myMethod(params)
        .send({ from: myAccount, gas: 10000000 });
    
    let txHash = receipt.transactionHash;
    ...
    
    // await saveToDb(thHash, ...)
    
    this.setState({ dateToDisplay: myVar.publishDate, loading: false });
    

    In my opinion, this makes the code less complex and easier to follow what's going on and make sense of it.