Files
outline/app/hooks/useRequest.ts
Tom MoorandHemachandar a4ee81fa19 OAuth server cloud compatibility (#9091)
* Revert "Add recency boost to search results (#9038)" (#9065)

This reverts commit 2bc47cfcef.

* fix: Double fetch on refactored paginated list (#9068)

* fix: Store Linear workspace logo only when it's available (#9072)

* Extract subdomain auth redirect (#9070)

* Extract subdomain auth redirect

* docs

* Switch Linear to actor=app method (#9074)

* Basic /authorize framework for cloud auth

* Handle logged out OAuth apex

---------

Co-authored-by: Hemachandar <132386067+hmacr@users.noreply.github.com>
2025-04-29 22:43:21 -04:00

66 lines
1.8 KiB
TypeScript

import * as React from "react";
import useIsMounted from "./useIsMounted";
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;
/** Whether the request has completed - useful to check if the request has completed at least once. */
loaded: 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.
* @param makeRequestOnMount Whether to make the request when the component mounts.
* @returns An object containing the request state and a function to start the request.
*/
export default function useRequest<T = unknown>(
requestFn: () => Promise<T>,
makeRequestOnMount = false
): RequestResponse<T> {
const isMounted = useIsMounted();
const [data, setData] = React.useState<T>();
const [loading, setLoading] = React.useState<boolean>(false);
const [loaded, setLoaded] = React.useState<boolean>(false);
const [error, setError] = React.useState();
const request = React.useCallback(async () => {
setLoading(true);
try {
const response = await requestFn();
if (isMounted()) {
setData(response);
setError(undefined);
setLoaded(true);
}
return response;
} catch (err) {
if (isMounted()) {
setError(err);
}
} finally {
if (isMounted()) {
setLoading(false);
}
}
return undefined;
}, [requestFn, isMounted]);
React.useEffect(() => {
if (makeRequestOnMount) {
void request();
}
}, []);
return { data, loading, loaded, error, request };
}