Files
outline/app/hooks/useRequest.ts
T
Tom Moor 4a2d36e2fa chore: Remove useIsMounted guards that only avoid the unmounted setState warning (#13843)
React 18+ no longer warns on setState after unmount, so the guards in
useRequest, useIdle, ActionButton, useDocumentSave and MultiplayerEditor are
removed. The Mentions guards protect an editor transaction against a destroyed
node view, so they are replaced with an effect-scoped cancel flag. Both
useIsMounted hook files are deleted.

Closes #13839
2026-09-21 22:37:27 -04:00

60 lines
1.8 KiB
TypeScript

import { useState, useCallback, useEffect } 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;
/** 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 [data, setData] = useState<T>();
const [loading, setLoading] = useState<boolean>(false);
const [loaded, setLoaded] = useState<boolean>(false);
const [error, setError] = useState<unknown>();
const request = useCallback(async () => {
setLoading(true);
try {
const response = await requestFn();
setData(response);
setError(undefined);
setLoaded(true);
return response;
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
return undefined;
}, [requestFn]);
useEffect(() => {
if (makeRequestOnMount) {
void request();
}
// Only ever request on mount, later changes to the request function are
// surfaced through the returned `request` for the caller to invoke.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { data, loading, loaded, error, request };
}