9

I am trying to create a UserContext to be accessible to all class components in the React app. I am receiving the following error.

ReferenceError: Cannot access 'UserContext' before initialization

App.js

import React, { createContext } from 'react';
export const UserContext = createContext(null);
function App() {
  return (

    <div className="App">
      <UserContext.Provider value={null}>
        <PageRoutes />
      </UserContext.Provider>
    </div>

  );
}

export default App;

LoginPage.js

import React, { Component } from 'react';
import { UserContext } from './App';

class MasterLoginPage extends Component {
    static contextType = UserContext;
    constructor(props) {
        super(props);
        this.state = {
            username: null,
            loggedIn: false
        }

// logic to work with username, password authentication

  render() {

    return (
        <div>
            // logic for rendering login page
          {
            this.state.loggedIn &&
            <UserContext.Provider value={this.state.username} />
          }
        </div>
  }
}

MasterLoginPage.contextType = UserContext;

export default MasterLoginPage;

PageRoutes.js

import React from 'react';

export default () => (
<BrowserRouter>
    <Switch>
      <Route exact path="/login" component={LoginPage} />
      <Route exact path="/home" component={Home}/>
    </Switch>
</BrowserRouter>
);

Home.js

import React from 'react';

export default class Home extends React.Component {
  // I want to put this user in a state variable in this component  
}
  1. Why am I getting reference error as I have already defined it in App.js ?
  2. If I have to store the userContext value in a state variable in some other class component say Home.js then how do I do that ?
Ashish Mysterio
  • 177
  • 1
  • 5
  • 13
  • Thats not how you access Context values, you need to use Consumer, please read the docs – Dennis Vash Oct 08 '20 at 06:03
  • That's the second part. Please can you follow on the first question. Why is there an initialization error ? Without that I won't be able to use the Provider and Consumer. @DennisVash – Ashish Mysterio Oct 08 '20 at 14:55
  • I think its related to code that you don't show, please see how to make a reproducible example, better make a sandbox, [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Dennis Vash Oct 08 '20 at 14:58
  • 1
    I'm having the same exact issue even after following the docs. https://reactjs.org/docs/context.html#classcontexttype – Mike Becatti Feb 23 '21 at 13:55

3 Answers3

1

Call the UserContext within the render block. Let me know if that works

1

That error seems to be caused by a circular dependency. What I did to solve that error was to create the Context outside the Provider file. Try to do this:

UserContext.js

import React from 'react';
export const UserContext = React.createContext();

LoginPage.js

static contextType = UserContext;

or

MasterLoginPage.contextType = UserContext;

not both.

The only thing you need to do is to import UserContext.js

Nelston
  • 68
  • 6
0

I would recommend to create a component to wrap the routes directly as:

WithUser.jsx

import React, { createContext } from 'react';
const UserContext = createContext(null);

export default (props) => {
    <UserContext.Provider value={null}>
        { props.children }
    </UserContext.Provider>
};    

then on:

PageRoutes.jsx

import React from 'react';

export default () => (
    <BrowserRouter>
        <Switch>
            <WithUser>
                <Route exact path="/login" component={LoginPage} />
                <Route exact path="/home" component={Home}/>
            </WithUser>
        </Switch>
    </BrowserRouter>
);

in case you want to make available the Context for both routes, if not, just wrap the one you want to use it.