Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 1121 | Rev 1358 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import { useState, useEffect } from 'react'
import { axios } from '../utils'
import { useDispatch } from 'react-redux'
import { addNotification } from '../redux/notification/notification.actions'

const useFetch = (url = '', defaultValue = null) => {
  const [data, setData] = useState(defaultValue)
  const [isLoading, setIsLoading] = useState(true)
  const dispatch = useDispatch()

  const getResources = (url = '') => {
    if (!url) return

    setIsLoading(true)

    axios
      .get(url)
      .then(({ data }) => {
        if (!data.data) {
          setData(data)
          return
        }

        if (!data.success) {
          const errorMessage =
            typeof data === 'string'
              ? data
              : Object.entries(data)
                  .map(([key, value]) => `${key}: ${value}`)
                  .join(', ')
          throw new Error(errorMessage)
        }

        setData(data.data)
      })
      .catch((err) => {
        dispatch(addNotification({ style: 'danger', msg: err.message }))
      })
      .finally(() => setIsLoading(false))
  }

  useEffect(() => {
    getResources(url)
  }, [url])

  return {
    data,
    mutate: setData,
    isLoading
  }
}

export default useFetch