Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading