Rev 14843 | AutorÃa | Comparar con el anterior | Ultima modificación | Ver Log |
import axios from 'axios'
import { useState, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { addNotification } from '../redux/notification/notification.actions'
function useDataFetching({ url = '', params = null }) {
const [loading, setLoading] = useState(true)
const [results, setResults] = useState([])
const dispatch = useDispatch()
useEffect(() => {
const fetchData = async () => {
try {
const { data } = await axios.get(url, { params })
if (!data.success) {
typeof data.data === 'string'
?
dispatch(addNotification({
style: 'danger',
msg: data.data
}))
: Object.entries(data.data).map(([key, value]) =>
value.map(err =>
dispatch(addNotification({
style: 'danger',
msg: `${key}: ${err}`
}))
)
)
setLoading(false)
return
}
setLoading(false)
setResults(data.data)
} catch (error) {
setLoading(false)
dispatch(addNotification({
style: 'danger',
msg: error
}))
return
}
setLoading(false)
}
fetchData()
}, [])
return {
loading,
results
}
}
export default useDataFetching