DEV Community

Aboucodeur
Aboucodeur

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)

useEffect(()=>{
    if(token){
      // 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

Discussion (0)