web3-react icon indicating copy to clipboard operation
web3-react copied to clipboard

'Error: useWeb3React can only be used within the Web3ReactProvider component' triggered for child component

Open fmontserrat opened this issue 3 years ago • 2 comments

<Web3ReactProvider connectors={initConnectors(networksConfig)}>
   <ComponentA>
</Web3ReactProvider>

This case works as expected.

However when trying to use useWeb3React in a child of ComponentA, the context is undefined.

NOTE: In ComponentA, the hook works perfectly but not further down:

const ComponentA => <ComponentB>here</ComponentB>
const ComponentB => {
useWeb3React <= Error: useWeb3React can only be used within the Web3ReactProvider component`
}

note: v6 allowed useWeb3React in further nested components.

fmontserrat avatar Jun 07 '22 08:06 fmontserrat

useWeb3React should be available for any child of a Web3ReactProvider component, no matter how deeply nested. if you have a repro where this is not the case, happy to take a look

NoahZinsmeister avatar Jun 08 '22 20:06 NoahZinsmeister

Update: Apologies, it was nested hooks rather than nested components which didn't work.

Was using

<Web3ReactProvider connectors={...}>
   <ComponentA>
       <ComponentB/>
   </ComponentA>
</Web3ReactProvider>

With ComponentB using a hook

useBlah()

Inside that hook, useWeb3React returned the error above.

Flattening the hooks solved the issue (FYI that setup used to work with v6)

fmontserrat avatar Jun 14 '22 16:06 fmontserrat