简体   繁体   中英

While running my next.js app that is using solidity smart contracts, I am getting "Cannot read properties of undefined" error

I was running my next.js app and trying to fetch user I am getting "cannot read properties of undefined" error

在此处输入图像描述

And following error in the console在此处输入图像描述

Below is the code I was using

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've changed import ethers from 'ethers' to import {ethers} from 'ethers' and now I'm facing this error

在此处输入图像描述

If unable to understand properly or if you want to see the whole codebase then this is the link to the github repo

https://github.com/ChiragDogra/ewitter/blob/userIssue/dapp/hooks/useEwitter.ts

believe or not I just had that issue.

the problem is how you are importing ethers . Should be

 import { ethers } from "ethers";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM