DEV Community


Posted on


React router private Routes

import React from "react"
import {Outlet,Navigate} from "react-router-dom"
import {useJwt} from "react-jwt" // decode token
import jsCookie from "js-cookie" // store cookie if login

const ProtectedRoutes = () =>{
  const {state} = useAppState() // consum the context

// add persistent in route in application
const retrieveToken = jsCookie.get("token")
const {decodeToken} = useJwt(retrievesToken)

      // persist route and update app state like user informations
      dispatch({type : "Auth/Ok"}) //state.isAuth :true
      dispatch({type : "Users/Ok" , payload : {users : ...decodeToken}}) 

 return (state.isAuth || token ) ? <Outlet/> : <Navigate to="/"/>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Advice For Junior Developers

Advice from a career of 15+ years for new and beginner developers just getting started on their journey.