Skip to content
Advertisement

I am trying to use the react hook useContext() but its not working

i am trying to use the useContext hook for the first time and i am not getting the name displayed on screen, i have never used useContext ever before, so pls a little bit of explination of my mistake will be appreciated. Here is the code: (edit: added App.js)

AuthContext.js

const AuthContext = createContext()


export default AuthContext;


export const AuthProvider = ({children}) => {
    return (
        <AuthContext.Provider value={{'name':"Dennis"}}>
            {children}
        </AuthContext.Provider>
    )
}

Header.js

import React, { createContext, useContext } from 'react'
import { Link } from 'react-router-dom'
import AuthContext from '../context/AuthContext'


const Header = () => {
  let { name } = useContext(AuthContext)
  return (
    <div>
        <Link to="/">Home</Link>
        <span>  </span>
        <Link to="/login">Login</Link>
        <h1>Hello {name}</h1>

    </div>
  )
}

export default Header

App.js

import './App.css';
import {
  BrowserRouter,
  Routes,
  Route,
} from "react-router-dom";
import HomePage from './pages/HomePage';
import LoginPage from './pages/LoginPage';
import Header from './components/Header';
import PrivateRoute from './utils/PrivateRoute'
import AuthProvider from './context/AuthContext';


function App() {
  return (
    <div className="App">
      <BrowserRouter>
      <AuthProvider>
        <Header />
          <Routes>

            <Route path="/" element={ <PrivateRoute> <HomePage /> </PrivateRoute>} />
            <Route path="/login" element={<LoginPage />} />
            
          </Routes>
        </AuthProvider>
      </BrowserRouter>
    </div>
  );
}
export default App;

i have added the error screenshotenter image description here

Advertisement

Answer

import AuthProvider from './context/AuthContext';

Instead of the above, you have to import the AuthProvider like below since you have used named export for AuthProvider in the AuthContext.js file.

import { AuthProvider } from './context/AuthContext';
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement