Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 708 | Ir a la última revisión | | 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
    setData(null)
14
 
15
    axios
16
      .get(url)
17
      .then((response) => {
18
        const { success, data } = response.data
19
 
20
        if (!success) {
21
          const errorMessage =
22
            typeof data === 'string'
23
              ? data
24
              : Object.entries(data)
25
                  .map(([key, value]) => `${key}: ${value}`)
26
                  .join(', ')
27
          throw new Error(errorMessage)
28
        }
29
 
30
        setData(data)
31
      })
32
      .catch((err) => {
33
        dispatch(addNotification({ style: 'danger', msg: err.message }))
34
      })
35
      .finally(() => setIsLoading(false))
36
  }
37
 
38
  useEffect(() => {
39
    getResources(url)
40
  }, [])
41
 
42
  return {
43
    data,
44
    isLoading
45
  }
46
}
47
 
48
export default useFetch