0

I have a parent component that can use useContext() to return the context, but if it's child component uses useContext() it returns the initial context (null in this case) and not the actual context.

I have no idea why this is happening because the parent component is wrapped in the provider, so the child must also have access to it.

Here's the code:

ApolloContext.js

import { createContext } from 'react';

export const ApolloContext = createContext(null);

index.js

    <ApolloProvider client={client} store={store}>
      <Router>
        <ApolloContext.Provider value={client}>
            <App scopes={scopes} userId={userId} />
        </ApolloContext.Provider>
      </Router>
    </ApolloProvider>,

Parent component:

import { ApolloContext } from "../context/apollo/ApolloContext";

const ParentComponent = () => {
console.log(useContext(ApolloContext)) // <- returns client
...

return (
  <Child />
 )
}

Child component

import { ApolloContext } from "../context/apollo/ApolloContext";

const Child = () => {
 console.log(useContext(ApolloContext)) // <- returns null
...
 return (
  <div> hello </div>
)};
Noob
  • 754
  • 3
  • 10
  • 27
  • Show your `ApolloProvider` .... [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Dennis Vash May 13 '21 at 14:47
  • And all component tree, it depends where the components are rendered, try reproduce in a sandbox – Dennis Vash May 13 '21 at 14:48
  • Why is there an `ApolloProvider` and then again a nested `ApolloContext.Provider` ? Are the two not related at all ? Generally a wrapper Provider class like `ApolloProvider` returns a `ApolloContext.Provider` component so alone `ApolloProvider` suffices. – Lakshya Thakur May 13 '21 at 14:49

0 Answers0