Skip to content

Instantly share code, notes, and snippets.

@tararoutray
Created October 18, 2022 02:35
Show Gist options
  • Save tararoutray/9220b4f06e2f588c1d14a700d19d4a8f to your computer and use it in GitHub Desktop.
Save tararoutray/9220b4f06e2f588c1d14a700d19d4a8f to your computer and use it in GitHub Desktop.
import React, { useEffect, useState } from "react";
import { Route, useNavigate } from "react-router-dom";
const ProtectedRoute = (props) => {
const navigate = useNavigate();
const [isLoggedIn, setIsLoggedIn] = useState(false);
const checkUserToken = () => {
const userToken = localStorage.getItem('user-token');
if (!userToken || userToken === 'undefined') {
setIsLoggedIn(false);
return navigate('/auth/login');
}
setIsLoggedIn(true);
}
useEffect(() => {
checkUserToken();
}, [isLoggedIn]);
return (
<React.Fragment>
{
isLoggedIn ? props.children : null
}
</React.Fragment>
);
}
export default ProtectedRoute;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment