fix: styles
This commit is contained in:
26
src/hooks/useApi.ts
Normal file
26
src/hooks/useApi.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
type ApiFunction<T> = () => Promise<{ data: T }>;
|
||||
|
||||
export function useApi<T>(apiFunction: ApiFunction<T>) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const response = await apiFunction();
|
||||
setData(response.data);
|
||||
} catch (err) {
|
||||
setError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, [apiFunction]);
|
||||
|
||||
return { data, loading, error };
|
||||
}
|
||||
56
src/lib/apiClient.ts
Normal file
56
src/lib/apiClient.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// Function to get the token from local storage or state management
|
||||
const getToken = () => localStorage.getItem('authToken');
|
||||
|
||||
const apiClient = axios.create({
|
||||
// Define the base URL for all API requests
|
||||
baseURL: 'https://api.yourapp.com/v1',
|
||||
|
||||
// Set a timeout for requests (e.g., 10 seconds)
|
||||
timeout: 10000,
|
||||
|
||||
// Set default headers
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// --- Request Interceptor ---
|
||||
// This runs BEFORE each request is sent
|
||||
apiClient.interceptors.request.use(
|
||||
(config) => {
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
// Add the authorization token to the headers
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
// Handle request errors
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
|
||||
// --- Response Interceptor ---
|
||||
// This runs AFTER a response is received
|
||||
// TODO: set global post api logic
|
||||
// apiClient.interceptors.response.use(
|
||||
// (response) => {
|
||||
// // Any status code within the 2xx range will trigger this function
|
||||
// return response;
|
||||
// },
|
||||
// (error) => {
|
||||
// // Handle common errors globally
|
||||
// if (error.response?.status === 401) {
|
||||
// // e.g., redirect to login page if unauthorized
|
||||
// console.error("Unauthorized! Redirecting to login...");
|
||||
// // window.location.href = '/login';
|
||||
// }
|
||||
// return Promise.reject(error);
|
||||
// }
|
||||
// );
|
||||
|
||||
export default apiClient;
|
||||
Reference in New Issue
Block a user