Proyectos de Subversion LeadersLinked - SPA

Rev

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

Rev 3407 Rev 3416
Línea 1... Línea 1...
1
import { useState, useEffect } from 'react'
1
import { 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";
4
import { axios } from '@utils'
5
import { useApi } from "./useApi";
5
import { asyncLogout } from '@store/auth/auth.actions'
6
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 6... Línea 11...
6
import { addNotification } from '@store/notification/notification.actions'
11
};
7
 
-
 
8
export function useFetch(url, defaultValue = {}) {
12
 
9
  const [data, setData] = useState(defaultValue)
-
 
10
  const [isLoading, setIsLoading] = useState(true)
-
 
11
  const dispatch = useDispatch()
-
 
12
 
-
 
13
  const handleError = (response) => {
-
 
14
    const { success, data } = response.data
-
 
15
 
-
 
16
    if (!data) {
-
 
17
      return response.data
-
 
18
    }
-
 
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
    return data
-
 
31
  }
-
 
32
 
-
 
33
  const getResources = (url) => {
-
 
34
    if (!url) return
13
export function useFetch(url, defaultValue = {}) {
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
      })
14
  const { data, loading, error, execute } = useApi(getResources(url), {
46
      .finally(() => setIsLoading(false))
-
 
47
  }
15
    autoFetch: true,
48
 
-
 
49
  const refetch = () => getResources(url)
-
 
Línea 50... Línea 16...
50
 
16
  });
51
  const mutate = (data) => setData(data)
17
  const dispatch = useDispatch();
-
 
18
 
-
 
19
  useEffect(() => {
-
 
20
    if (error) {
52
 
21
      dispatch(addNotification({ style: "danger", msg: err.message }));
Línea 53... Línea 22...
53
  useEffect(() => {
22
      if (err.message.includes("sesión")) dispatch(asyncLogout());
54
    getResources(url)
-
 
55
  }, [url])
23
    }
56
 
24
  }, [error]);
57
  return {
25
 
58
    data,
26
  return {
59
    mutate,
27
    data: data ?? defaultValue,