0

Let's say I have this solidity code:

uint256 public num;

  function setNum(uint256 _num) public {
    num= _num;
  }

How would I create a react form that passes a value to the smart contract and retrieves the result?

Any help would be greatly appreciated.

2 Answers 2

0

You can use events. Here is an example:

  uint256 public num;
  Event NumberSetted(uint256 num);

  function setNum(uint256 _num) public {
    num= _num;
  emit NumberSetted(_num);
  }

You can learn more about it from docs

0

First, you have to install and import Web3 and connect your website with the Metamask extension.

The code for connecting your website with Metamask is:

if (Web3.givenProvider) {
      const web3 = new Web3 (Web3.givenProvider);
      await Web3.givenProvider.enable();
} else {
        console.log("Please Install Metamask extension");
}

After connecting with Metamask, you have to access the methods of your contract.

const contract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);
const accounts= await web3.eth.getAccounts();

To interact with your contract function, you can use the async function like this:

const updateNumber = async(number) => {
  try {
    const receipt = await contract.methods.setNum(number).send({from: accounts[0]});
  } catch (error) {
    console.log ('error: ', error);
  }
};

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.