I'm trying to use context. but I'm having that error Put my 2 files below
import React, { useState, useEffect, Consumer, useContext } from 'react'
//import MessageContract from '../build/Message.json'
import WalletProvider from '../context/WalletContext'
function App() {
const {
web3Provider,
address,
isConnected,
chainId,
networkId,
errorMsg,
connectWallet
} = useContext(WalletProvider)
return (
<WalletProvider>
<div className="App">
<button className="button is-primary" onClick={connectWallet}>
{address && address.length > 0
? `Connected: ${address.substring(
0,
6
)}...${address.substring(38)}`
: "Connect Wallet"}
</button>
</div>
</WalletProvider>
);
}
export default App;
And the context file
import React, {useState, useEffect, createContext} from 'react';
import Web3 from 'web3';
const WalletContext = createContext("")
export const WalletProvider = ({props}) => {
const [web3Provider, setWeb3Provider] = useState(null)
const [address, setAddress] = useState(null)
const [isConnected, setIsConnected] = useState(false)
const [chainId, setChainId] = useState('')
const [networkId, setNetworkId] = useState('')
const [errorMsg, setErrorMsg] = useState('')
const connectWallet = async () => {
if( !isConnected) {
try {
// connect web3
let web3 = new Web3(window.ethereum)
setWeb3Provider(web3)
// get acounts
const accounts = await web3.eth.getAccounts()
setAddress(accounts[0])
if ( accounts ) {
let networkId = await web3.eth.net.getId()
setNetworkId(networkId)
let chainId = await web3.eth.getChainId()
setChainId(chainId)
}
} catch (error) {
setErrorMsg(error)
}
setIsConnected(true)
}
}
return (
<WalletContext.Provider value= {{
web3Provider,
address,
isConnected,
chainId,
networkId,
errorMsg,
connectWallet
}}>
{props.children}
</WalletContext.Provider>
)
}
export default WalletContext;
CodePudding user response:
This line is incorrect
const {...} = useContext(WalletProvider)
useContext
takes the context as an argument, not the provider.