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

JavaScript regex substitution not functioning as expected

My JavaScript code contains a string var str = '<at id="11:12345678">@robot</at> ping'; I am trying to remove a specific part of this string <at id="11:12345678">@ To achieve this, I am using the following code snippet: var ...

Getting started with Preact.js: Setting up an auto re-run server similar to React.js

Is there a way to set up a development server for Preact similar to how React operates with npm start? Currently, when I use the same command with Preact, it launches a static server and requires manual restart each time I make changes to my project. Here ...

What could be causing the updated JavaScript file to not run on a live Azure website using ASP.NET MVC?

After making a minor adjustment to my JavaScript file on my deployed ASP MVC website hosted on Azure, I decided to redeploy everything. However, upon checking the resource files, I noticed that the JavaScript had indeed been changed, but the behavior of th ...

Tips for preventing automatic zoom on mobile devices

Check out this link for the test: The current layout of the site is exactly how I want it to be presented. However, I am facing an issue where if I set the viewport meta tag to <meta name="viewport" content="width=device-width, initial-scale=1"> i ...

Could you provide suggestions on how to update the content of an HTML tag within a Vue component?

I am new to Vue.js and struggling to grasp its concepts. I am interested in finding a way for my custom Vue component (UnorderedList) to manipulate the content within it. For example, if I have <p> tags inside my component like this : <UnorderedL ...

What is the best method to loop through this object with JavaScript?

Suppose I have the following data: let testData = { 'numGroup1': [[(1, 2, 3, 4, 5), (5, 6, 7, 8, 9)]], 'numGroup2': [[(10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]] }; What is the best approach to iterate through this data using Jav ...

Iterating through a nested array of objects to merge and accumulate values

Just started learning Javascript. I've been trying to wrap my head around it for hours, looking at examples, but still struggling. I'm working with an array of objects that have nested properties which I need to loop through and consolidate. ...

WebStorm not recognizing NodeJS Core Modules in External Libraries

As a newcomer to NodeJS and WebStorm, I am currently diving into a tutorial on creating an Express app. In the tutorial, the instructor always gets prompted with "Configure NodeJS Core Module Sources" including the URL nodeJS.org when creating a new NodeJ ...

Exploring the Functionality of Algolia Places within a Next.js Application

Currently, I am working on integrating the Algolia Places functionality into my next.js project using TypeScript. To begin, I executed npm install places.js --save Next, I inserted <input type="search" id="address-input" placeholder ...

Iterate through JSON and dynamically populate data

My goal is to dynamically populate content by iterating through JSON data using jQuery. First, an Ajax request is made Then the data is looped through to create HTML tags dynamically A div container with the class "product-wrapper" is created for each J ...

What is the best way to execute playwright on localhost using GitHub Actions?

I have been attempting to execute playwright End-to-End tests for github-actions, but so far my efforts have been unsuccessful. - name: Run build and start run: | yarn build:e2e yarn start:e2e & - name: Run e2e run: ...

Ways to retrieve the data received from an axios.post request in the server-side code

Currently, I am working on a project that involves using React for the frontend and Spring Boot for the backend. However, I am facing an issue with retrieving data that I have sent using Axios from the frontend to the backend. The code snippet below show ...

NodeJS: Error - Unexpected field encountered in Multer

Having trouble saving an image in a SQL database and getting the error message MulterError: Unexpected field. It worked fine in similar cases before, so I'm not sure what's wrong. H E L P!! <label id="divisionIdLabel" for="divis ...

What is the best way to extract data from two dropdown menus and send it to separate URLs?

I need assistance with extracting the selected year value from the first dropdown. I would like to append this value to the URL of the header page and also to the options in the second dropdown. This way, when I select a PHP page from the second dropdown ...

Tips for transferring query parameters in a redirect within NextJS

Whenever a user tries to access a page without authentication, I automatically redirect them to the login page. After that, I want to display a message to inform them of why they were redirected. However, I am encountering an issue with passing parameter ...

Using Javascript regex to capture the image name from a CSS file

As I work with JavaScript regex, my goal is to extract the image name and extension as a capture group of CSS properties. Criteria Must start with "url" Followed by brackets Optional quotes inside brackets The location can include path information Must ...

Trigger Element Upon Click

Forgive me in advance for the lack of quality in this question, but I'll proceed anyway: All I want is for an element to slide open when clicked with a mouse! That's all! More specifically, I am looking for a single menu item that, upon clickin ...

Sending an array and an object simultaneously through a single ajax request

I previously inquired about passing an object to an ajax request for my rest service. Now I am wondering if it's possible to pass both an array and an object within a single ajax request. Any insights on this matter would be greatly valued. ...

Combining outcomes from two separate jQuery AJAX requests and implementing deferred/promise functionality

I am struggling to combine the outcomes of two jQuery AJAX requests. Despite reviewing similar questions here, none seem to provide a solution. Each ajax call (2 in total) has a success function that calls the createStatusView function and passes it the ...

Utilize Meteor and Mongo to access a nested array object in a template with spacebars

I am trying to populate the content of a textarea by extracting data from a nested array. In my helper function, I have specified the document id and the element id. The goal is to extract the content of the text field from the findOne result and display i ...