By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – React Router protected route wrapper does not detect the new authentication state from AuthProvider
JavaScript

Javascript – React Router protected route wrapper does not detect the new authentication state from AuthProvider

Admin
Last updated: 2024/01/12 at 2:40 PM
Admin
Share
3 Min Read
React Router protected route wrapper does not detect the new authentication state from AuthProvider

Problem:

Here it’s shown the most basic implementation of authentication in React-Router v6. loggedIn flag in PrivateRoutes does not change when updated to true after updating context, and so the private routes cannot be accessed when navigating to them. Why is that?

Contents
Problem:Solution:
import './App.css';
import {
  BrowserRouter,
  Navigate,
  Outlet,
  Route,
  Routes,
  useNavigate
} from 'react-router-dom';
import React, { useState } from 'react';

function App() {
  return (
    <div>
      <AuthProvider>
        <BrowserRouter>
          <Routes>
            <Route path="/" element={<HomePage />} />

            <Route element={<PrivateRoutes />}>
              <Route path="/secret" element={<SecretPage />} />
              {/** ... Other protected pages ...*/}
            </Route>
            
          </Routes>
        </BrowserRouter>
      </AuthProvider>
    </div>
  );
}

function PrivateRoutes() {
  const { loggedIn } = useAuth();

  return loggedIn ? <Outlet />: <Navigate to="/" />
}

function HomePage() {
  const navigate = useNavigate();

  return <>
    <h1>Home page</h1>
    <button onClick={() => navigate('/secret')}>
      Go to secret page
    </button>
  </>
}

function SecretPage() {
  return <>
    <h1>Secret Page</h1>
  </>
}

const AuthContext = React.createContext()

const AuthProvider = ({ children }) => {
  const { loggedIn, signIn } = useAuth()

  return
    <AuthContext.Provider value={loggedIn}>
      
      {/** 
       * Button to trigger sign in and showing the
       * current status.
      */}
      <button onClick={signIn}>LogIn</button>
      <h2>Logged In: {loggedIn.toString()}</h2>
      <p>-----------------------</p>

      {children}
    </AuthContext.Provider>
}

const useAuth = () => {
  const [loggedIn, setLoggedIn] = useState(false)

  const signIn = () => {

    {/** sign in logic ....*/}

    setLoggedIn(true);
  };

  return { loggedIn, signIn };
}

export default App;

Solution:

useAuth is a React hook and React hooks don’t share internal state. Each instance of useAuth has its own independent loggedIn state.

Refactor the AuthProvider to hold the loggedIn state and update the useAuth hook to consume the provided context value. This is how all instances of useAuth get the same value.

const AuthContext = React.createContext();

const AuthProvider = ({ children }) => {
  const [loggedIn, setLoggedIn] = useState();

  const signIn = () => {
    {/** sign in logic ....*/}
    setLoggedIn(true);
  };

  return (
    <AuthContext.Provider value={{ loggedIn, signIn }}>
      {/** 
       * Button to trigger sign in and showing the
       * current status.
      */}
      <button onClick={signIn}>LogIn</button>
      <h2>Logged In: {loggedIn.toString()}</h2>
      <p>-----------------------</p>

      {children}
    </AuthContext.Provider>
  );
}

const useAuth = () => React.useContext(AuthContext);
function PrivateRoutes() {
  const { loggedIn } = useAuth();

  if (loggedIn === undefined) {
    return null; // or loading indicator/spinner/etc
  }

  return loggedIn
    ? <Outlet />
    : <Navigate to="/" replace />;
}

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Dispatching captured events works but not when I've created them myself (HumanBenchmark) Javascript – Dispatching captured events works but not when I’ve created them myself (HumanBenchmark)
Next Article In AlpineJS, is it possible to create x-model tags which bind to objects in an array? Javascript – In AlpineJS, is it possible to create x-model tags which bind to objects in an array?
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?