Proyectos de Subversion LeadersLinked - SPA

Rev

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

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