Rev 3427 | AutorÃa | 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);
setData(result);
return result;
} catch (err) {
setError(err);
throw err;
} finally {
setLoading(false);
}
},
[apiFunction]
);
useEffect(() => {
if (autofetch) {
execute(...initialArgs)
.then(onSuccess)
.catch(onError);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [autofetch, execute, ...autofetchDependencies, ...initialArgs]);
return { loading, data, error, execute };
}