I'm trying to link my smart contract to a boilerplate react frontend as follows:
import React, { useState, useEffect } from "react";
import MyContract from "./contracts/MyContract.json";
import getWeb3 from "./getWeb3";
const App = () => {
const [value, setValue] = useState(undefined);
const [web3, setWeb3] = useState(undefined);
const [accounts, setAccounts] = useState([]);
const [contract, setContract] = useState([]);
useEffect(() => {
const init = 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 = MyContract.networks[networkId];
const contract = new web3.eth.Contract(
MyContract.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.
setWeb3(web3);
setAccounts(accounts);
setContract(contract);
console.log(contract);
} 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);
}
};
init();
}, []);
useEffect(() => {
const load = async () => {
// Stores a given value, 5 by default.
await contract.methods
.mintToken("sample string")
.send({ from: accounts[1] });
// Get the value from the contract to prove it worked.
const response = await contract.methods.ownerOf("1").call();
setValue(response);
// Update state with the result.
};
if (
typeof web3 !== "undefined" &&
typeof accounts !== "undefined" &&
typeof contract !== "undefined"
) {
load();
}
}, [web3, accounts, contract]);
if (typeof web3 === "undefined") {
return <div>Loading Web3, accounts, and contract...</div>;
}
return (
<>
<p>{value}</p>
</>
);
};
export default App;
I was using the truffle react box and tried to convert the old react syntax to useReact() and useEffect() hooks. When I run this I get the following errors: Uncaught (in promise) TypeError: contract.methods is undefined and Uncaught (in promise) Error: No "from" address specified in neither the given options, nor the default options.
But I console logged the contract object and the methods property has all the functions of the smart contract. How can I fix these errors and properly integrate my smart contract with the react frontend?