I encountered an issue while operating my next.js application which utilizes solidity smart contracts. The error message "Cannot read properties of undefined" was displayed during the process

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

Answer №1

Interestingly, I recently encountered that exact issue.

The main issue lies in the way you are importing the ethers library. It should be done like this:

 import { ethers } from "ethers";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which sorting algorithm is most suitable for handling strings, numbers, or a combination of both in JavaScript?

This situation is quite intriguing to me. Suppose we have an array defined as: var x = [1, 50, 2, 4, 2, 2, 88, 9, 10, 22, 40]; Now, if we run the code x.sort();, it will fail to sort properly. On the other hand, if the array is defined as: var x = ["dog ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

Utilize the synchronization feature of ES6 Promises in Jasmine with the then/catch method

I have an angular controller that needs to be tested. This controller utilizes a service to fetch data from a server, and the service returns ES6 Promises. function MyController($scope, MyService) { $scope.doSomething = function () { MyService.foo() ...

Tips for effectively utilizing axios without Vue.js CLI (for instance, in JS Fiddle)

Currently, I am immersing myself in the world of vue.js. To get a better understanding of the dependencies, I have chosen not to utilize the Vue cli just yet, opting for JS Fiddle instead. My next goal is to interact with an API using axios. Here is a glim ...

The NodeJS module 'request' is producing symbols instead of expected HTML content

Currently, I am delving into the world of Nodejs and experimenting with web scraping using node.js. My tools of choice are the node modules request and cheerio. However, when I attempt to request a URL, instead of receiving the HTML body, I get strange s ...

Steps for resetting the counter to 0 following an Ajax Refresh or Submission to the database

I have been working on a code that successfully sends multiple data to a MySQL Database using JQuery Ajax. Everything works smoothly, but I encountered an issue when trying to refresh the page with ajax and add a new record; it populates the number of time ...

Leverage the power of Next.js to dynamically render a specific section of an HTML webpage

I want to incorporate Next.js into a specific section of my website, while the rest of the site is built using different frameworks that are not even based on React. I aim to use Next.js within a <div id="nextjs_div">...</div> element ...

Body Zoom Browser

My website features buttons for zooming in and out, labeled as A + and A-. I wanted to make sure that the entire body of the website could be magnified easily. That's why I came up with this code: <html> <body> <style> .cont ...

Object data is not being received by the defaultValue in React Hook Form

I am currently utilizing React Hook Form to facilitate the process of editing/updating data. I retrieve my data from zustand with a value type of any, and then proceed to save it as the defaultValue in React Hook Form. However, when attempting to acquire v ...

What techniques are most effective for creating unit tests in a Node.js environment?

One of the challenges I am facing is writing a unit test for a module where I load a mustache template file. To tackle this, I am exploring the use of mocha, chai, and rewire. Below is an excerpt from my module.js: var winston = require('winston&apo ...

How can I utilize React hook to choose multiple items?

I am currently working on developing a next js application. As part of this project, I have been tasked with creating a custom dropdown select menu using react hooks, specifically useState. The code I have written for this is as follows. Data- export defa ...

How can data be transferred from a parent to a child component in Angular?

I'm facing an issue trying to pass the selected value from a dropdownlist in a user interface. I have a parent component (app.component.html) and a child component (hello.component.html & hello.component.ts). My goal is to transfer the option val ...

Struggling with updating scope values when binding data in Angular (particularly with a slider)

Currently, I am utilizing Angular to develop a tool that can take user input from a slider tool and dynamically update an "estimate" field whenever the values are adjusted. However, I'm encountering an issue where the data is only binding in one direc ...

Issue with PHP Upload: Index is undefined

Having Trouble with PHP Upload: Encountered an issue: Undefined index: file in Error on line: $count = count($_FILES['file']['name']); Tried numerous codes to fix this error, but none have worked so far PHP Code: <?php $count ...

Unpredictable hovering actions when interacting with nested items within the hover layer

Imagine a scenario where we have the following elements: A container that holds everything A baseDiv inside that container // Let's create a base layer var container = document.getElementById('container') var baseDiv = document.createEl ...

Ways to rejuvenate an Angular element

Last month, I was called in to rescue a website that was in chaos. After sorting out the major issues, I am now left with fixing some additional features. One of these tasks involves troubleshooting an angular code related to videos and quizzes on certain ...

Is PHP loaded prior to the `html body`?

I'm facing a unique challenge where I am currently transferring variables from a PHP page to hidden HTML inputs. The values are extracted from these hidden inputs using a JavaScript function that is called in the following manner: <body onload=" ...

Unable to populate an array with JSON elements within a for loop triggered by useEffect

In my code, there is an issue with the array candleRealTimeDataQueue not updating correctly. Below is the snippet of the problematic code: let candleCurrentJSONDataWS = null; var candleRealTimeDataQueue = []; let tempDateTime = null; let ca ...

Tips for retrieving a variable from an XML file with saxonjs and nodejs

I came across an xml file with the following structure: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE agent SYSTEM "http://www.someUrl.com"> <myData> <service> <description>Description</description> < ...

Explain what mongoose and Schema are at the beginning, just once

Hello, I am currently working on a Node.js application using Express and MongoDB. In order to utilize MongoDB and schema, I have to define Mongoose and schema in all of my routing JavaScript files. However, I would like to only define them once. As I am ne ...