1

I'm trying to create a small web3.0 app, using next.js. I have deployed my contract on rinkeby test network, and I am able to check the functionalities using Remix, work properly. I have also worked on similar projects on react, they also work as exepected. But when I try to connect I am currently facing the following issue (maybe this has something to do with Server side rendering of next.js or HttpProvider, I'm not sure):

TypeError: Cannot read properties of undefined (reading 'Contract')
  3 | import address from './build/campaignHubAddress.json';
  4 | 
> 5 | const instance = new web3.eth.Contract(contract.abi, address.campaignHubAddress);
    |                     ^
  6 | export default instance;

web3.js

import Web3 from 'web3';
let web3;
if (typeof window !== 'undefined' && typeof window.ethereum !== 'undefined') {
    window.ethereum.request({ method: "eth_requestAccounts" });
    web3 = new Web3(window.ethereum);
} else {
    const provider = new Web3.providers.HttpProvider(
        'https://rinkeby.infura.io/v3/3ed112ee6c4d42a09e485ddb5eec5fa2'
    );
    web3 = new Web3(provider);
}
export default web3;

instance.js

import web3 from 'web3';
import contract from './build/CampaignHub.json';
import address from './build/campaignHubAddress.json';

const instance = new web3.eth.Contract(contract.abi, address.campaignHubAddress);
export default instance;

index.js

import React from 'react';
import web3 from '../web3';
import instance from '../instance';

class Index extends React.Component{
    static async getInitialProps(){
        const campaigns = await instance.methods.getCampaigns().call();
        return { campaigns };
    }
    render() {
        return (
            <>
                <p>Hello, this is the test page for now.</p>
                <p>Web3 version: {web3.version}</p>
                <p>List of all the running campaigns: {this.props.campaigns} </p>
            </>
        );
    }
}
export default Index; 

This seems basic, but I have been stuck at it for some time now. Need help. Please ask for any clarification if required.

1 Answer 1

0

After scratching a lot of head, I found that the error was in instance.js. While importing import web3 from 'web3'; I should have done import web3 from './web3';

Wow, just wasted a lot of time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.