SyedFouzan's picture
{
ffb4c35 verified
Raw History Blame Contribute Delete
1.51 kB
import { useState, useEffect } from 'react';
import axios from 'axios';
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:8080/api';
export const useFetch = (url, options = {}) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const response = await axios.get(`${API_BASE_URL}${url}`, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
...options.headers
}
});
setData(response.data);
setError(null);
} catch (err) {
setError(err.response?.data?.message || 'An error occurred');
} finally {
setLoading(false);
}
};
if (url) {
fetchData();
}
}, [url]);
const refetch = () => {
const fetchData = async () => {
try {
setLoading(true);
const response = await axios.get(`${API_BASE_URL}${url}`, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
...options.headers
}
});
setData(response.data);
setError(null);
} catch (err) {
setError(err.response?.data?.message || 'An error occurred');
} finally {
setLoading(false);
}
};
fetchData();
};
return { data, loading, error, refetch };
};