1

I'm trying to do something pretty simple using React, but I can't understand what's going on.

const A = await myContract.getA() // A = 0
  
myContract
       .setA(1) // should set A = 1 => confirmed by blockExplorer!
       .then(tx => tx.wait())
       .then(async () => {
             const a = await myContract.getA() // A = 0!   
        })
       .catch()

If I refresh the page right after the tx.wait(), then the first statement returns A = 1 / meaning that the tx was successful and the state is changed, so why the state fetched after the tx is the old one??

Also added a setTimeout like with 10 seconds to be sure that's not the issue...

Ideas??? thanks

EDIT: Created a setInterval to constantly call the contract every second. Eventually, the state gets updated, but it takes forever. Any ideas why takes so long to the state to change when using metamask?

If I call a server that uses @truffle/hdwallet-provider to get the state, changes are reflected almost instantly!

2 Answers 2

1

When chaining promises each then has to return a promise for the subsequent then to proceed sequentially.

However in your code both the then methods are listening to the same promise returned by setA. As a result they wont be executed sequentially. Kindly check this explanation on how chaining promises work to get a clear picture. https://javascript.info/promise-chaining

As @bluebunny suggested chaining then tx.wait is the right way to address the issue

0

You might have more success chaining the second .then call to tx.wait() -- that way, the second then() is for sure firing off /after/ the transaction has confirmed, rather than potentially before.

Ie., (txn => txn.wait(1).then(do stuff))

1
  • Yeah... actually that was exactly how I did it... Tried async/await... you name it. But I think that the problem is with react and references or smth like that. I created a separed Button, and call the function on click. THAT response contains the changed state
    – fseb
    Jan 14, 2022 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.