Rev 3432 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { axios } from '@utils';
import { asyncLogout } from '@store/auth/auth.actions';
import { addNotification } from '@store/notification/notification.actions';
export function useFetch(url, defaultValue = {}) {
const [data, setData] = useState(defaultValue);
const [isLoading, setIsLoading] = useState(true);
const dispatch = useDispatch();
const handleError = (response) => {
const { success, data } = response.data;
if (!data) {
return response.data;
}
if (!success) {
const errorMessage =
typeof data === 'string'
? data
: Object.entries(data)
.map(([key, value]) => `${key}: ${value}`)
.join(', ');
throw new Error(errorMessage);
}
return data;
};
const getResources = (url) => {
if (!url) return;
setIsLoading(true);
axios
.get(url)
.then((response) => handleError(response))
.then((data) => setData(data))
.catch((error) => {
dispatch(addNotification({ style: 'danger', msg: error.message }));
if (error.message.includes('sesión')) dispatch(asyncLogout());
})
.finally(() => setIsLoading(false));
};
const refetch = () => getResources(url);
const mutate = (data) => setData(data);
useEffect(() => {
getResources(url);
}, [url]);
return {
data,
mutate,
isLoading,
refetch
};
}