0

I am trying to access the web3 object injected into my browser by Metamask. I am using custom rpc (). I can see my accounts and correct balances in Metamask. I have the following code:

//web3.js

import Web3 from "web3";

let web3;

if (typeof window !== "undefined" && window.web3 !== "undefined") {
  web3 = new Web3(window.web3.currentProvider);
} else {
  const provider = new Web3.providers.WebsocketProvider("ws://localhost:7545");
  web3 = new Web3(provider);
}

export default web3;

This is imported and used in my app.js file:

import React, { Component } from "react";

import web3 from "./web3";

import SimpleOwnable from "./contracts/SimpleOwnable.json";
import contract from "truffle-contract";
const MyContract = contract(SimpleOwnable);

//using web3 here causes error
MyContract.setProvider(web3.currentProvider);

...
class App extends Component {
  async componentDidMount() {
    //this logs correctly
    console.log(MyContract);

    const deployed = await MyContract.deployed();
    //this does not
    console.log(deployed);
  }
...
render(){
...
}

I commented the import web3 from "./web3"; statement and changed web3.currentProvider to window.web3.currentProvider. Both the console logs worked as expected. Can someone please explain what am I doing wrong.

There are similar questions but their answers don't solve my problem.

versions: web3 1.0.0-beta.55 Truffle v5.0.18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.