Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3660 | | Comparar con el anterior | Ultima modificación | Ver Log |

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