[Ethereum] Contract method: Error: Provider not set or invalid

dapp-developmentweb3js

I'm building a Dapp using MetaMask. However, I'm getting an error when I try to call a method on my contract.

Here's the simplified code:

var web3 = new Web3(web3.currentProvider);
var contract = new web3.eth.Contract(contractData.abi);
contract.options.address = address;
contract.methods.getName().call().then(name => console.log(name))

This throws the following error:

Unhandled rejection Error: Provider not set or invalid

Digging through the debugger, it seems that the RequestManager doesn't have a provider set. However, I can't figure out how that provider should be set?

Best Answer

Have you set MetaMask to whatever test network you are using? If testrpc, select in Metamask that you want to connect to LocalHost 8545, and if using Ganache, you can create a custom RPC to connect to LocalHost 7545. From there, use the seed phrase given from testrpc or Ganache to "restore"/connect. This should pull in your accounts, and let you connect properly to a provider.