Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3481 | Rev 3484 | 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);
31
        setData(result);
32
        onSuccess(result);
33
        return result;
34
      } catch (err) {
35
        setError(err);
36
        onError(err);
37
      } finally {
38
        setLoading(false);
39
      }
40
    },
41
    [apiFunction]
42
  );
43
 
44
  useEffect(() => {
45
    if (autofetch) {
46
      execute(...initialArgs)
47
        .then(onSuccess)
48
        .catch(onError);
49
    }
50
  }, [autofetch, execute, ...autofetchDependencies, ...initialArgs]);
51
 
52
  return { loading, data, error, execute };
53
}