local-fake-api
Version:
A simple async local mock API without backend.
48 lines (47 loc) • 1.57 kB
JavaScript
import { useEffect, useState } from "react";
function useRestApi({ queryId, apiCall, initValue, willCall = true, }) {
const [apiData, setApiData] = useState(initValue);
const [apiError, setApiError] = useState(undefined);
const [isLoading, setIsLoading] = useState(true);
const [renderCount, setRenderCount] = useState(0);
useEffect(() => {
async function getApiData() {
try {
setIsLoading(true);
const response = await apiCall();
const { success, data, error } = response;
if (success && data !== undefined) {
setApiData(data);
setApiError(undefined);
}
else {
setApiError(error !== null && error !== void 0 ? error : new Error("Unknown API error"));
}
}
catch (err) {
setApiError(err);
}
finally {
setIsLoading(false);
}
}
if (willCall || renderCount > 0) {
void getApiData();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [willCall, queryId, renderCount]);
const redo = () => setRenderCount((prev) => prev + 1);
return {
isLoading: willCall && isLoading,
isError: !!apiError,
hasError: !!apiError,
success: !apiError,
apiData,
apiError,
setApiData,
run: redo,
reCall: redo,
redo,
};
}
export { useRestApi };