1

In React Typescript (.tsx file), I'm trying to use web3.eth.sign to validate an account. The signature is being generated properly, but I can't seem to get the signature out of the callback function.

The following code is inside a functional component:

const [signature, setSignature] = useState<string>('')

function Sign() {
   const web3 = window.web3

   web3.personal.sign(
      nonce,
      accountId,
      function(err: any, signed: string) {
         if (!err) {
            console.log(`${signed}`)
            setSignature(signed) 
            console.log(`Signature = ${signature}`)
         }
   })
}

Sign()
// some other code that uses signature variable

signed is printing a valid signature, but signature is not being set. This is a big problem. For the rest of my code to work I need to get the signed variable and set it to an external signature variable where I can pass it to other functions.

Any ideas?

2 Answers 2

0

One solution: Instead of UseState, put your signature code inside the anonymous function.

Instead of

const [signature, setSignature] = useState<string>('')

function Sign() {
   const web3 = window.web3

   web3.personal.sign(
      nonce,
      accountId,
      function(err: any, signed: string) {
         if (!err) {
            console.log(`${signed}`)
            setSignature(signed) 
            console.log(`Signature = ${signature}`)
         }
   })
}

Sign()
// some other code that uses signature variable

Do this:

function Sign() {
   const web3 = window.web3

   web3.personal.sign(
      nonce,
      accountId,
      function(err: any, signed: string) {
         if (!err) {
            console.log(`${signed}`)
            // some other code that uses signature variable, now denoted as signed
         }
   })
}

Sign()

It doesn't exactly solve the problem, but it worked for my use case and might work for yours if you're having a similar issue.

1
  • with which version of web3.js is this working? I am using (this)[cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js] and I get Error: Returned error: Method not found at Object.ErrorResponse (errors.js:28) at index.js:303 at XMLHttpRequest.i.onreadystatechange (index.js:98)
    – Suisse
    Apr 5, 2021 at 15:19
0

This is not about web3, it's about ReactJS. The state change performed by setSignature is not immediately reflected, but it will be in the next render cycle.

In React, state updates are typically batched for performance reasons, meaning that multiple state updates that occur within the same event loop cycle are grouped together and applied at once. Additionally, updates to state are not guaranteed to be immediate, as they may be queued and applied at a later time.

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.