Rev 3483 | Rev 3496 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import { useState, useCallback, useEffect } from 'react';
export function useApi(
apiFunction,
options = {
autofetch: false,
autofetchDependencies: [],
initialArgs: [],
onSuccess: () => {},
onError: () => {}
}
) {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const {
autofetch = false,
autofetchDependencies = [],
initialArgs = [],
onSuccess = () => {},
onError = () => {}
} = options;
const execute = useCallback(
async (...args) => {
setLoading(true);
setData(null);
setError(null);
try {
const result = await apiFunction(...args);
console.log(result);
setData(result);
onSuccess(result);
return result;
} catch (err) {
setError(err);
onError(err);
} finally {
setLoading(false);
}
},
[apiFunction]
);
useEffect(() => {
if (autofetch) {
execute(...initialArgs)
.then(onSuccess)
.catch(onError);
}
}, [autofetch, execute, ...autofetchDependencies, ...initialArgs]);
return { loading, data, error, execute };
}