Click here to view original web page at stackoverflow.com
In TransactionContext.js (see code below), I am getting a no ethereum object error in the connectWallet function whenever i submit data to the ethereum blockchain. However, I have already connected metamask to the website. There should be an ethereum object. How do i resolve this error?
(https://i.stack.imgur.com/7y9X4.jpg)
import React, {useEffect, useState} from 'react'
import {ethers} from 'ethers'
import { contractABI, contractAddress } from "../utils/constants"
export const TransactionContext = React.createContext()
const { ethereum } = window;
const createEthereumContract = () => {
const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();
const transactionsContract = new ethers.Contract(contractAddress, contractABI, signer);
return transactionsContract;
};
//have to also create our context because where are we going to call this - we need to have a
//specific place where it's going to serve a purpose for that reason
//function to check if a wallet is connected at the start
export const TransactionProvider = ({children}) => {
const [formData, setformData] = useState({ addressTo: "", amount: "", keyword: "", message: "" });
const [currentAccount, setCurrentAccount] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [transactionCount, setTransactionCount] = useState(localStorage.getItem("transactionCount"));
const [transactions, setTransactions] = useState([]);
//handleChange func interact with inputs except the event
const handleChange = (e, name) => {
setformData((prevState) => ({ ...prevState, [name]: e.target.value }));
};
const getAllTransactions = async () =>{
//check if browser has metamask installed
try {if(!ethereum) return alert("Please install metamask")
const transactionContract = createEthereumContract();
const availableTransactions = await transactionContract.getAllTransactions()
//change structure of data
const structuredTransactions = availableTransactions.map((transaction)=>({
addressTo: transaction.receiver,
addressFrom: transaction.sender,
timestamp: new Date(transaction.timestamp.toNumber() * 1000).toLocaleString(),
message: transaction.message,
keyword: transaction.keyword,
amount: parseInt(transaction.amount._hex) / (10 ** 18)
}))
} catch(error){
console.log(error);
}
}
const checkIfWalletIsConnected = async() =>{
try{
if(!ethereum) return alert("Please install metamask")
const accounts = await ethereum.request({method:'eth_accounts'})
console.log(accounts)
if(accounts.length){
setCurrentAccount(accounts[0])
getALLtransactions()
} else {
console.log('No accounts found')
}
} catch(error){
console.log(error)
throw new Error("No ethereum object")
}
}
const checkIfTransactionsExist = async () => {
try {
const transactionsContract = createEthereumContract()
const transactionsCount = await transactionsContract.getTransactionCount()
window.localStorage.setItem("transactionCount",transactionCount)
} catch(error) {
}
}
{/*function for connecting the account */}
const connectWallet = async () => {
try {
if (!ethereum) return alert("Please install MetaMask.");
const accounts = await ethereum.request({ method: "eth_requestAccounts", });
setCurrentAccount(accounts[0]);
window.location.reload();
} catch (error) {
console.log(error);
throw new Error("No ethereum object");
}
}
const sendTransaction = async () => {
try {
if (ethereum) {
const { addressTo, amount, keyword, message } = formData;
const transactionsContract = createEthereumContract();
const parsedAmount = ethers.utils.parseEther(amount);
await ethereum.request({
method: "eth_sendTransaction",
params: [{
from: currentAccount,
to: addressTo,
gas: "0x5208",
value: parsedAmount._hex,
}],
});
const transactionHash = await transactionsContract.addToBlockchain(addressTo, parsedAmount, message, keyword);
setIsLoading(true);
console.log(`Loading - ${transactionHash.hash}`);
await transactionHash.wait();
console.log(`Success - ${transactionHash.hash}`);
setIsLoading(false);
const transactionsCount = await transactionsContract.getTransactionCount();
setTransactionCount(transactionsCount.toNumber());
window.location.reload();
} else {
console.log("No ethereum object");
}
} catch (error) {
console.log(error);
throw new Error("No ethereum object");
}
}
useEffect(()=>{
checkIfWalletIsConnected()
checkIfTransactionsExist()
},[])
return(
<TransactionContext.Provider value={{connectWallet, currentAccount,formData,handleChange,sendTransaction,transactions,isLoading}}>
{children}
</TransactionContext.Provider>)}