|
1 |
| -import React from 'react'; |
2 | 1 | import Navbar from 'app/components/navbar';
|
3 | 2 | import BasicRoutes from 'app/routes/BasicRoutes';
|
4 | 3 | import './index.scss';
|
5 |
| -import { Toaster } from 'react-hot-toast'; |
| 4 | +import toast, { Toaster } from 'react-hot-toast'; |
| 5 | +import { getUser } from './api/user'; |
| 6 | +import { useLocation, useNavigate } from 'react-router-dom'; |
| 7 | +import { useQuery } from 'react-query'; |
| 8 | +import { useContext } from 'react'; |
| 9 | +import UserContext from './context/user/userContext'; |
| 10 | + |
6 | 11 | function App() {
|
| 12 | + |
| 13 | + const navigate= useNavigate(); |
| 14 | + const location = useLocation(); |
| 15 | + const currentPath = location.pathname; |
| 16 | + const userContext= useContext(UserContext); |
| 17 | + const token= localStorage.getItem('token'); |
| 18 | + const checklogin= async ()=>{ |
| 19 | + if(token!=null){ |
| 20 | + try{ |
| 21 | + const userData= await getUser(token); |
| 22 | + userContext?.setUsername(userData.data.message); |
| 23 | + if(currentPath=="/login"){ |
| 24 | + navigate("/"); |
| 25 | + } |
| 26 | + } catch(e){ |
| 27 | + localStorage.removeItem('token') |
| 28 | + if(currentPath!="/login"){ |
| 29 | + toast.error("Session expired") |
| 30 | + navigate("/login"); |
| 31 | + } |
| 32 | + } |
| 33 | + }else{ |
| 34 | + if(currentPath!="/login"){ |
| 35 | + toast.error("Not authenticated") |
| 36 | + navigate("/login") |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + const {} = useQuery("login", checklogin, { |
| 41 | + enabled: true, |
| 42 | + staleTime: Infinity |
| 43 | + }) |
| 44 | + |
7 | 45 | return (
|
8 | 46 | <>
|
9 | 47 | <Navbar />
|
|
0 commit comments