While working on my next.js app and attempting to fetch user data, I encountered the "cannot read properties of undefined" error.
https://i.stack.imgur.com/SBPBf.png
I also received the following error in the console https://i.stack.imgur.com/JBtbO.png
Here is the code snippet that caused the issue:
import Ewitter from './Ewitter.json';
import { ethers } from 'ethers';
import { useState, useEffect } from 'react';
const ContractABI = Ewitter.abi;
const ContractAddress = '0x5FbDB2315678afecb367f032d93F642f64180aa3';
const Ethereum = typeof window !== 'undefined' && (window as any).ethereum;
const getEwitterContract = () => {
const provider = new ethers.providers.Web3Provider(Ethereum);
const signer = provider.getSigner();
const EwitterContract = new ethers.Contract(
ContractAddress,
ContractABI,
signer
);
return EwitterContract;
};
const useEwitter = () => {
// const Ewitter = getEwitterContract();
const [currentAccount, setCurrentAccount] = useState<string>('');
const [currentUser, setCurrentUser] = useState<string>('');
const connect = async () => {
try {
if (!Ethereum) {
alert('Please install MetaMask');
return;
}
const accounts = await Ethereum.request({
method: 'eth_requestAccounts',
});
if (accounts.length === 0) {
alert('Please unlock MetaMask');
return;
}
const account = accounts[0];
console.log('connected to account: ', account);
setCurrentAccount(account);
} catch (errors) {
console.log(errors);
}
};
useEffect(() =>{
if(!Ethereum){
console.log("No ethereum wallet found, please install metamask")
return ;
}
connect();
}, []);
useEffect(() =>{
if(currentAccount){
getUser();
}
}, [currentAccount])
const getUser = async ()=>{
const contract = getEwitterContract();
const user = await contract.getUser(currentAccount);
const {avatar, bio, name, username, wallet} = user;
console.log(user);
return user;
}
return { connect, account: currentAccount };
};
export default useEwitter;
#Update1
I modified import ethers from 'ethers'
to import {ethers} from 'ethers
and now I'm facing this error:
https://i.stack.imgur.com/lsTaT.png
If you are having trouble understanding or would like to see the entire codebase, you can visit the GitHub repository at:
https://github.com/ChiragDogra/ewitter/blob/userIssue/dapp/hooks/useEwitter.ts