Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 707 | Rev 758 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
707 stevensc 1
import { useState, useEffect } from 'react'
2
import { axios } from '../utils'
3
import { useDispatch } from 'react-redux'
4
import { addNotification } from '../redux/notification/notification.actions'
5
 
6
const useFetch = (url = '', defaultValue = null) => {
7
  const [data, setData] = useState(defaultValue)
8
  const [isLoading, setIsLoading] = useState(false)
9
  const dispatch = useDispatch()
10
 
11
  const getResources = (url = '') => {
12
    setIsLoading(true)
13
 
14
    axios
15
      .get(url)
16
      .then((response) => {
17
        const { success, data } = response.data
18
 
19
        if (!success) {
20
          const errorMessage =
21
            typeof data === 'string'
22
              ? data
23
              : Object.entries(data)
24
                  .map(([key, value]) => `${key}: ${value}`)
25
                  .join(', ')
26
          throw new Error(errorMessage)
27
        }
28
 
29
        setData(data)
30
      })
31
      .catch((err) => {
32
        dispatch(addNotification({ style: 'danger', msg: err.message }))
33
      })
34
      .finally(() => setIsLoading(false))
35
  }
36
 
37
  useEffect(() => {
38
    getResources(url)
39
  }, [])
40
 
41
  return {
42
    data,
43
    isLoading
44
  }
45
}
46
 
47
export default useFetch