How can I protect routes in ReactJs?

I am trying to protect my routes with reactjs and hooks. However there is an issue. The user and the token don’t update even if make setUser() and setToken() with new values inside them. And it leads to the fact that I can’t protect my route. So I hope someone can help me with this!!!

import React, { useState,useEffect} from 'react'
import { Redirect } from 'react-router-dom'

function ProtectedRoutes(props) {
    const [user, setUser] = useState({})
    const [token, setToken] = useState(null)
    const Component = props.component

    useEffect(() => {
        //
            const getUser = async () => {
        
                //Retreive Token
                const sessionToken = await sessionStorage.getItem('token')
                setToken(sessionToken)

                //Fetch User    
                const response = await fetch(`${process.env.REACT_APP_URL}api/users/me`, {
                    method: 'get',
                    headers: new Headers({
                        "x-auth-token": `${token}`
                    })
                })
                const result = await response.json();
                setUser(result)
                //
            
       }
        getUser()
        
        return ()=> {}
       
    },[token,user])
    
    //Token
    if (!token || Object.keys(user).length !== 2) {
        return <Redirect to={{ pathname: '/connexion' }} />
    }
    return <Component/>

}

export default ProtectedRoutes

66 thoughts on “How can I protect routes in ReactJs?”

Leave a Comment