Comments, appointments adjustments, fixed some issues
This commit is contained in:
@@ -2,10 +2,14 @@
|
||||
|
||||
import { createContext, useContext, useState, useEffect, useCallback } from "react";
|
||||
|
||||
//Auth context
|
||||
//Stores the logged in user, token, and auth actions
|
||||
const AuthContext = createContext(null);
|
||||
|
||||
//Key used to save the token in localStorage
|
||||
const TOKEN_KEY = "auth_token";
|
||||
|
||||
//Fetches the current user from the backend using the stored token
|
||||
async function fetchCurrentUser(token) {
|
||||
const res = await fetch("/api/v1/auth/me", {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
@@ -14,11 +18,13 @@ async function fetchCurrentUser(token) {
|
||||
return res.json();
|
||||
}
|
||||
|
||||
//Provides auth state to all child components
|
||||
export function AuthProvider({ children }) {
|
||||
const [user, setUser] = useState(null);
|
||||
const [token, setToken] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
//Re-fetches the user info using the current or a newly provided token
|
||||
const refreshUser = useCallback(async (providedToken) => {
|
||||
const activeToken = providedToken ?? token;
|
||||
if (!activeToken) {
|
||||
@@ -41,6 +47,7 @@ export function AuthProvider({ children }) {
|
||||
return userInfo;
|
||||
}, [token]);
|
||||
|
||||
//On first load, check if a token was saved and try to restore the session
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(TOKEN_KEY);
|
||||
if (!stored) {
|
||||
@@ -57,6 +64,7 @@ export function AuthProvider({ children }) {
|
||||
.finally(() => setLoading(false));
|
||||
}, [refreshUser]);
|
||||
|
||||
//Logs the user in and saves the token
|
||||
const login = useCallback(async (username, password) => {
|
||||
const res = await fetch("/api/v1/auth/login", {
|
||||
method: "POST",
|
||||
@@ -84,6 +92,7 @@ export function AuthProvider({ children }) {
|
||||
return userInfo;
|
||||
}, [refreshUser]);
|
||||
|
||||
//Creates a new account and logs the user in right away
|
||||
const register = useCallback(async ({ username, password, email, firstName, lastName, phone }) => {
|
||||
const res = await fetch("/api/v1/auth/register", {
|
||||
method: "POST",
|
||||
@@ -118,6 +127,7 @@ export function AuthProvider({ children }) {
|
||||
return userInfo;
|
||||
}, [refreshUser]);
|
||||
|
||||
//Clears the token and user from memory and localStorage
|
||||
const logout = useCallback(() => {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
setToken(null);
|
||||
@@ -130,6 +140,7 @@ export function AuthProvider({ children }) {
|
||||
);
|
||||
}
|
||||
|
||||
//Hook to access auth state, must be used inside an AuthProvider
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) {
|
||||
|
||||
Reference in New Issue
Block a user