0

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?

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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