main
|
Last change
on this file since 24a2a2a was 24a2a2a, checked in by Filip Gavrilovski <filipgavrilovski28@…>, 6 months ago |
|
add login page
|
-
Property mode
set to
100644
|
|
File size:
1.4 KB
|
| Line | |
|---|
| 1 | import {
|
|---|
| 2 | createContext,
|
|---|
| 3 | useContext,
|
|---|
| 4 | useEffect,
|
|---|
| 5 | useState,
|
|---|
| 6 | type Dispatch,
|
|---|
| 7 | type ReactNode,
|
|---|
| 8 | type SetStateAction,
|
|---|
| 9 | } from "react";
|
|---|
| 10 | import axiosInstance, {
|
|---|
| 11 | refreshTokenMethod,
|
|---|
| 12 | scheduleTokenRefresh,
|
|---|
| 13 | } from "../api/axiosInstance";
|
|---|
| 14 | import { type User } from "../types";
|
|---|
| 15 |
|
|---|
| 16 | interface AuthContextType {
|
|---|
| 17 | user: User | undefined;
|
|---|
| 18 | setUser: Dispatch<SetStateAction<User | undefined>>;
|
|---|
| 19 | isAuthLoading: boolean;
|
|---|
| 20 | }
|
|---|
| 21 |
|
|---|
| 22 | const AuthContext = createContext<AuthContextType>({
|
|---|
| 23 | user: undefined,
|
|---|
| 24 | setUser: () => {},
|
|---|
| 25 | isAuthLoading: false,
|
|---|
| 26 | });
|
|---|
| 27 |
|
|---|
| 28 | interface AuthProviderProps {
|
|---|
| 29 | children: ReactNode;
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | export const AuthProvider = ({ children }: AuthProviderProps) => {
|
|---|
| 33 | const [user, setUser] = useState<User | undefined>(undefined);
|
|---|
| 34 | const [isAuthLoading, setIsAuthLoading] = useState(true);
|
|---|
| 35 |
|
|---|
| 36 | useEffect(() => {
|
|---|
| 37 | const fetchUserDetails = async () => {
|
|---|
| 38 | try {
|
|---|
| 39 | await refreshTokenMethod();
|
|---|
| 40 | const response = await axiosInstance.get<{
|
|---|
| 41 | tokenExpiresIn: number;
|
|---|
| 42 | user: User;
|
|---|
| 43 | }>("/auth/user");
|
|---|
| 44 | setUser(response.data.user);
|
|---|
| 45 | scheduleTokenRefresh(response.data.tokenExpiresIn);
|
|---|
| 46 | } catch (error) {
|
|---|
| 47 | setUser(undefined);
|
|---|
| 48 | } finally {
|
|---|
| 49 | setIsAuthLoading(false);
|
|---|
| 50 | }
|
|---|
| 51 | };
|
|---|
| 52 |
|
|---|
| 53 | fetchUserDetails();
|
|---|
| 54 | }, []);
|
|---|
| 55 |
|
|---|
| 56 | return (
|
|---|
| 57 | <AuthContext.Provider value={{ user, setUser, isAuthLoading }}>
|
|---|
| 58 | {children}
|
|---|
| 59 | </AuthContext.Provider>
|
|---|
| 60 | );
|
|---|
| 61 | };
|
|---|
| 62 |
|
|---|
| 63 | export const useAuth = () => useContext(AuthContext);
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.