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