Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3660 | Mostrar el archivo completo | | | Autoría | Ultima modificación | Ver Log |

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