Proyectos de Subversion LeadersLinked - SPA

Rev

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

Rev Autor Línea Nro. Línea
3481 stevensc 1
import { useState, useCallback, useEffect } from 'react';
2
 
3
export function useApi(
4
  apiFunction,
5
  options = {
6
    autofetch: false,
7
    autofetchDependencies: [],
8
    initialArgs: [],
9
    onSuccess: () => {},
10
    onError: () => {}
11
  }
12
) {
13
  const [data, setData] = useState(null);
14
  const [error, setError] = useState(null);
15
  const [loading, setLoading] = useState(false);
16
  const {
17
    autofetch = false,
18
    autofetchDependencies = [],
19
    initialArgs = [],
20
    onSuccess = () => {},
21
    onError = () => {}
22
  } = options;
23
 
24
  const execute = useCallback(
25
    async (...args) => {
26
      setLoading(true);
27
      setData(null);
28
      setError(null);
29
      try {
30
        const result = await apiFunction(...args);
3484 stevensc 31
        console.log(result);
3481 stevensc 32
        setData(result);
33
        onSuccess(result);
34
        return result;
35
      } catch (err) {
36
        setError(err);
37
        onError(err);
38
      } finally {
39
        setLoading(false);
40
      }
41
    },
42
    [apiFunction]
43
  );
44
 
45
  useEffect(() => {
46
    if (autofetch) {
47
      execute(...initialArgs)
48
        .then(onSuccess)
49
        .catch(onError);
50
    }
51
  }, [autofetch, execute, ...autofetchDependencies, ...initialArgs]);
52
 
53
  return { loading, data, error, execute };
54
}