Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3416 | Ir a la última revisión | Mostrar el archivo completo | | | Autoría | Ultima modificación | Ver Log |

Rev 3416 Rev 3432
Línea 1... Línea 1...
1
import { useEffect } from "react";
1
import { useState, useEffect } from 'react'
2
import { useDispatch } from "react-redux";
2
import { useDispatch } from 'react-redux'
Línea 3... Línea 3...
3
 
3
 
4
import { api } from "@api";
-
 
5
import { useApi } from "./useApi";
4
import { axios } from '@utils'
6
import { asyncLogout } from "@store/auth/auth.actions";
5
import { asyncLogout } from '@store/auth/auth.actions'
7
import { addNotification } from "@store/notification/notification.actions";
-
 
8
 
-
 
9
const getResources = async (url) => {
-
 
10
  return await api.get(url);
-
 
Línea 11... Línea 6...
11
};
6
import { addNotification } from '@store/notification/notification.actions'
12
 
7
 
13
export function useFetch(url, defaultValue = {}) {
8
export function useFetch(url, defaultValue = {}) {
14
  const { data, loading, error, execute } = useApi(getResources(url), {
-
 
15
    autoFetch: true,
9
  const [data, setData] = useState(defaultValue)
Línea 16... Línea 10...
16
  });
10
  const [isLoading, setIsLoading] = useState(true)
-
 
11
  const dispatch = useDispatch()
-
 
12
 
17
  const dispatch = useDispatch();
13
  const handleError = (response) => {
-
 
14
    const { success, data } = response.data
-
 
15
 
-
 
16
    if (!data) {
-
 
17
      return response.data
18
 
18
    }
-
 
19
 
-
 
20
    if (!success) {
-
 
21
      const errorMessage =
19
  useEffect(() => {
22
        typeof data === 'string'
-
 
23
          ? data
-
 
24
          : Object.entries(data)
20
    if (error) {
25
              .map(([key, value]) => `${key}: ${value}`)
-
 
26
              .join(', ')
-
 
27
      throw new Error(errorMessage)
-
 
28
    }
-
 
29
 
-
 
30
    return data
-
 
31
  }
-
 
32
 
-
 
33
  const getResources = (url) => {
-
 
34
    if (!url) return
-
 
35
 
-
 
36
    setIsLoading(true)
-
 
37
 
-
 
38
    axios
-
 
39
      .get(url)
-
 
40
      .then((response) => handleError(response))
-
 
41
      .then((data) => setData(data))
-
 
42
      .catch((error) => {
-
 
43
        dispatch(addNotification({ style: 'danger', msg: error.message }))
-
 
44
        if (error.message.includes('sesión')) dispatch(asyncLogout())
-
 
45
      })
-
 
46
      .finally(() => setIsLoading(false))
-
 
47
  }
-
 
48
 
-
 
49
  const refetch = () => getResources(url)
-
 
50
 
-
 
51
  const mutate = (data) => setData(data)
21
      dispatch(addNotification({ style: "danger", msg: err.message }));
52
 
Línea 22... Línea 53...
22
      if (err.message.includes("sesión")) dispatch(asyncLogout());
53
  useEffect(() => {
-
 
54
    getResources(url)
23
    }
55
  }, [url])
24
  }, [error]);
56
 
25
 
57
  return {
26
  return {
58
    data,
27
    data: data ?? defaultValue,
59
    mutate,