Set subscribe/unsubscribe state correctly for documents (#4266)

This commit is contained in:
Apoorv Mishra
2022-10-13 05:18:43 +05:30
committed by GitHub
parent 7199088d1b
commit 2708d429a9
2 changed files with 62 additions and 2 deletions

43
app/hooks/useRequest.ts Normal file
View File

@@ -0,0 +1,43 @@
import * as React from "react";
type RequestResponse<T> = {
/** The return value of the request function. */
data: T | undefined;
/** The request error, if any. */
error: unknown;
/** Whether the request is currently in progress. */
loading: boolean;
/** Function to start the request. */
request: () => Promise<T | undefined>;
};
/**
* A hook to make an API request and track its state within a component.
*
* @param requestFn The function to call to make the request, it should return a promise.
* @returns
*/
export default function useRequest<T = unknown>(
requestFn: () => Promise<T>
): RequestResponse<T> {
const [data, setData] = React.useState<T>();
const [loading, setLoading] = React.useState<boolean>(false);
const [error, setError] = React.useState();
const request = React.useCallback(async () => {
setLoading(true);
try {
const response = await requestFn();
setData(response);
return response;
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
return undefined;
}, [requestFn]);
return { data, loading, error, request };
}