DEV Community

Aboucodeur
Aboucodeur

Posted on

3 1

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

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more