Here's my solidity contract:
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
And heres' the React frontend:
import React, { Component } from "react";
import SimpleStorageContract from "./contracts/SimpleStorage.json";
import getWeb3 from "./getWeb3";
import "./App.css";
class App extends Component {
componentDidMount = async () => {
try {
// Get network provider and web3 instance.
const web3 = await getWeb3();
// Use web3 to get the user's accounts.
const accounts = await web3.eth.getAccounts();
// Get the contract instance.
const networkId = await web3.eth.net.getId();
const deployedNetwork = SimpleStorageContract.networks[networkId];
const instance = new web3.eth.Contract(
SimpleStorageContract.abi,
deployedNetwork && deployedNetwork.address,
);
// Set web3, accounts, and contract to the state, and then proceed with an
// example of interacting with the contract's methods.
this.setState({ web3, accounts, contract: instance });
} catch (error) {
// Catch any errors for any of the above operations.
alert(
`Failed to load web3, accounts, or contract. Check console for details.`,
);
console.error(error);
}
};
constructor(props) {
super(props);
this.state = {
storageValue: 0,
web3: null,
accounts: null,
contract: null
}
this.setValue = this.setValue.bind(this);
}
setValue(x) {
this.state.contract.methods.set(x).send({ from: this.state.accounts[0] });
}
render() {
if (!this.state.web3) {
return <div>Loading Web3, accounts, and contract...</div>;
}
return (
<div className="App">
<form onSubmit={(event) => {
event.preventDefault();
let x;
this.setValue(x);
}}>
<label>Enter value</label>
<input type="text" ref={(input) => { this.x = input }}/>
<button type="submit" >Set value</button>
</form>
</div>
);
}
}
export default App;
I'm trying to set the value of storeData from the frontend, but I just can't seem to get it to work.