Home > database >  Sharing context with a nested component, getting UserContext is not defined
Sharing context with a nested component, getting UserContext is not defined

Time:06-26

I am trying to share a service of some sort to a component that is nested inside another, but I'm getting an undefined error.

'UserContext' is not defined no-undef

This is my App.js:

import logo from './logo.svg';
import './App.css';
import React, {createContext} from "react";
import {
    BrowserRouter as Router,
    Routes,
    Route
} from "react-router-dom";
import TopPanel from "./components/topPanel/TopPanel";
import UserCtx from "./services/UserCtx";

function App() {

    const UserContext = createContext({});

    return (
        <Router>
            <UserContext.Provider value={new UserCtx()}>
                <TopPanel/>
            </UserContext.Provider>
            <Routes>
                ...
            </Routes>
        </Router>
    );
}

export default App;

Inside of the TopPanel component there is a Login component, which should consume the context:

import React, {useState, useContext} from "react";

function Login() {

    const userCtx = useContext(UserContext);

    ...
}

export default Login;

But it's apparently not getting passed on. What am I doing wrong please? It doesn't even look like it's passed on to the 1st level component.

Don't think it's relevant, but here's the context object:

import React from "react";

class UserCtx {

    isLoggedIn;
    token;

    constructor() {
        this.isLoggedIn = false;
    }

    logIn = (token) => {
       console.log("LOGGING IN!");
       this.isLoggedIn = true;
       this.token = token;
    }
}

export default UserCtx;

CodePudding user response:

The creation of the context should be outside of the component, this line const UserContext = createContext({}); should be outside of App component, and it should be export it:

export const UserContext = createContext({});

Make sure inside Login you import UserContext at the top, before doing what you have there:

import React, {useState, useContext} from "react";
import {UserContext} from "../../App"; // use the correct path

function Login() {

    const userCtx = useContext(UserContext);

    ...
}

export default Login;

CodePudding user response:

Think of UserContext object as an outside box that can be mounted to any other objects(components) in the tree structure objects of react. You should declare the context object outside your App component.

  • Related