Languages

React - why useContext returns undefined?

0 points
Asked by:
Hayley-Mooney
677

Take a look at these three components. Can some explain why Login component can't see the loginUser method from the authenticationService?

Everything seems right: passing context, imports and yet it returns undefined.

1. App component - in which I created AuthenticationContext and passed it to the Container using Provider.

2. Container component - in which I render Login component.

3. Login component - here I want to use loginUser from App's authenticationService but it's undefined.

2 answers
7 points
Answered by:
Root-ssh
178290

Look at your case, simple steps:

  1. App.js imports Login from './Components/Login'
  2. Login.js imports AuthenticationContext from '../App'
  3. AuthenticationContext is created in App.js with:
    export const AuthenticationContext = createContext();
    // AuthenticationContext doesn't exist in step 2 yet

Summary:

App imports Login and inside Login App is imported again - keep contexts in separated files.

0 commentsAdd comment
0 points
Answered by:
Aisha
418

Quick solution:

  • put context into a separate file

Sometimes importing a lot of files creates a cycle that leads to errors.

When I put context from the App into a separate file - contexts.js (which is a good practice) it worked.

0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join