jwt provider and common api utils

This commit is contained in:
2025-11-11 15:45:24 +05:30
parent 42fe31fc69
commit 90e6a85fff
4 changed files with 58 additions and 29 deletions

View File

@@ -1,12 +1,10 @@
import React, { createContext, useState, useEffect, useContext } from 'react';
import axios from 'axios';
import { AuthorModel } from "../types/models";
import { AuthContextModel } from "../types/contexts";
import { api } from '../utils/api';
import { AuthorModel } from '../types/models';
import { AuthContextModel } from '../types/contexts';
const AuthContext = createContext<AuthContextModel | undefined>(undefined);
const API_BASE = import.meta.env.VITE_API_BASE_URL;
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [currentUser, setCurrentUser] = useState<AuthorModel | null>(null);
const [authors, setAuthors] = useState<AuthorModel[]>([]);
@@ -20,7 +18,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
setLoading(true);
setError(null);
const res = await axios.post(`${API_BASE}/auth/login`, { email, password });
const res = await api.post('/auth/login', { email, password });
const { access_token, user } = res.data;
if (access_token) {
@@ -44,17 +42,13 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
setAuthors([]);
};
/** 🔹 Fetch all authors (requires valid JWT) */
/** 🔹 Fetch all authors (JWT handled by api interceptor) */
const refreshAuthors = async () => {
if (!token) return;
try {
setLoading(true);
setError(null);
const res = await axios.get<AuthorModel[]>(`${API_BASE}/authors`, {
headers: { Authorization: `Bearer ${token}` },
});
const res = await api.get<AuthorModel[]>('/authors');
setAuthors(res.data);
} catch (err: any) {
console.error('Failed to fetch authors:', err);
@@ -68,9 +62,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const fetchCurrentUser = async () => {
if (!token) return;
try {
const res = await axios.get<AuthorModel>(`${API_BASE}/auth/me`, {
headers: { Authorization: `Bearer ${token}` },
});
const res = await api.get<AuthorModel>('/auth/me');
setCurrentUser(res.data);
} catch (err: any) {
console.error('Failed to fetch current user:', err);
@@ -78,6 +70,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
};
/** 🔹 On mount, try to fetch user if token exists */
useEffect(() => {
if (token) fetchCurrentUser();
}, [token]);