Encountering a problem with web3Modal: Getting an error message saying "window is not defined" when trying to initialize a web

I have encountered an error while using Nextjs with Reactjs and Typescript. Interestingly, the code works perfectly fine without Typescript, but as soon as I introduce Typescript, I run into this issue.

Specifically, I am utilizing the useMemo hook in my implementation. I attempted moving its initialization outside of the function, yet the error persists regardless of the approach.

Included below is a snippet of the code that I am currently employing:

const INFURA_ID = process.env.REACT_APP_INFURA_ID;

const initWeb3 = (provider: any) => {
  const web3 = new Web3(provider);

  web3.eth.extend({
    methods: [
      {
        name: "chainId",
        call: "eth_chainId",
        outputFormatter: web3.utils.hexToNumber as any,
      },
    ],
  });

  return web3;
};

export function Web3UtilityProvider() {
  // ...remaining code

https://i.sstatic.net/A7V4l.png

Answer №1

It turned out that the issue I encountered was not directly related to JavaScript or TypeScript. While it worked fine with a ReactJS app utilizing CSR, my situation involved using NextJS where SSR caused an undefined window object error. To overcome this challenge, I implemented a solution by incorporating fallback (specifically useEffect).

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

Automating a login prompt with dual inputs using WebdriverIO: A step-by-step guide

I'm having trouble automating the login prompt as shown in the attached image. I've attempted to fill in both fields using WebdriverIO but so far have been unsuccessful. I explored using alert methods like browser.sendAlertText(), but none of the ...

Error Message: Angular 5 with SignalR (DefinitelyTyped) - '$' Not Found in Typings

I am currently working on implementing SignalR into my Angular 5 application. To do this, I added the following TypeScript type definitions from DefinitelyTyped: npm install --save @types/jquery npm install --save @types/signalr The version of Typescrip ...

Requiring Subclasses to Maintain Immutability

I have created a base class that contains various properties: class Component { readonly id: number readonly type: number } Now, I am looking to create some subclasses, such as: class HealthComponent extends Component { max_health: number, ...

Angular 2. @Input is not recognized as a valid property

Within my parent component, I have the following template: <ion-content> <blocks-banners-slideshow class="contentBlock" [config]="{ zone: 'mobile'}" [config_private]="{ url: 'url'}" [slideOptions]="{ loop: true, pager: true} ...

Creating an object for an HTTP POST request in an Angular app by utilizing the values of another object

Within my Angular application, I am working with a Job object and an Offer object. These are the interfaces I have defined: export interface IJob { id: number; title: string; description: string; employeeId?: number; managerId: string; imageU ...

Template URI parameters are being used in a router call

Utilizing the useRouter hook in my current project. Incorporating templated pages throughout the application. Implementing a useEffect hook that responds to changes in the router and makes an API call. Attempting to forward the entire URL to /api/${path ...

Updating the value of a dropdown in React Testing Library

When testing an input, the process is as follows: it('test input', () => { const { getByTestId, getByLabelText } = render(<MyComponent />); const myButton = getByTestId('submit-button'); expect(myButton).toBeInTh ...

What is the best way to implement a mixin reducer for functional typing?

Currently, I am in the process of learning typescript and facing challenges in understanding how to correctly type a reducer function that reduces functional mixins. Let's consider two functional mixins: type FooComposable = { foo: string; }; const ...

Issues with TypeScript: Difficulty locating names in HTML templates

I recently upgraded my Angular 7 code to Angular 9 by following the steps outlined in the Angular Upgrade guide. However, upon completion of the migration process, I started encountering numerous "Cannot find name" errors within the HTML templates of my co ...

When attempting to build the iOS app with Ionic, the error "Unable to access property toLowerCase of undefined" is

When attempting to build ios in Ionic3 using the command: ionic cordova build ios, I encounter the error "Cannot read property toLowerCase of undefined". Below is the log output with the --verbose flag: > ionic-app-scripts build --target cordova --pla ...

Filter an object within an array based on the index values of another array

Imagine a situation where users can select multiple items and remove them. This calls for two arrays: One containing checkbox values (checked status and index) The other holding the actual items that need to be filtered based on the checked values' ...

Enriching HtmlElement with a type property using TypeScript

Check out my TypeScript code snippet below: let script: HTMLElement = document.createElement("script"); script.appendChild(document.createTextNode(` { "json": "property" } `)); script.id = 'appContextModel'; document.body.appendChild(scr ...

Guide to accessing the content of pure ES6 modules directly in the Chrome console without the need for Webpack

Situation: When using tsc to compile code for es6, the scripts function properly once they are served from a server. However, I am unsure of how to access variables within modules through the console. The file names do not seem to be available as objects ...

Processing and transforming a TypeScript object results in an unexpected outcome

I have received an object that has the following structure: {\"key1\":{\"cluster_region\":\"centralus\"},\"key2\":{\"cluster_region\":\"westeurope ...

In Typescript, verify whether the request body is of type User; if not, an error should

Hey there, I'm facing a challenge while working on my project. Currently, I am utilizing express js to develop a rest api and my goal is to enable users to update their profiles. To start off, I have set up a User model: export type User = { emai ...

No response from NgClass after executing the function

In my NgClass function, I make use of an array that is populated in the ngOnInit lifecycle hook. Within ngOnInit, the prepareRezerwation() function creates a variable called colorRezerwation: this.nodeService.getRezerwations(this.minMax).subscribe(re ...

Retrieving data from child components within an array in another component using Angular

How can I assign the value of the variable 5 in Array(5) to another variable in this code? My goal: export class HelloComponent { @Input() page: number; active = 0; pages; constructor() { this.pages = Array(this.page) // instead of Array( ...

Updating Values in Angular Frontend: Modifying Backend Data in the Frontend Interface

Trying to tackle a problem in my Angular project that has me stumped. When the frontend loads, it fetches values using a GET request like so: getAll(fetch_id: string): Subject<Element[]> { this.dataSource.getData(fetch_id).subscribe((elements) => ...

Issue encountered: Upon executing 'ng add @angular/fire', an error was detected in the node_modules/firebase/compat/index.d.ts file while attempting to launch the Angular application

Recently, I decided to integrate Firebase into my project, but encountered a persistent error after installing the firebase module 'ng add @angular/fire' and running it with 'ng serve': Error: node_modules/firebase/compat/index.d.ts:770 ...

What could be causing the issue with my customized sorting in the Material-UI Data Grid component?

After integrating Material-UI's Data Grid Component with my API's JSON array, I had to create a RenderCell function to handle text overflow and include a button that directs Users to a different page. Additionally, I utilized the ValueGetter for ...