import { useState, useCallback, useEffect } from "react"; type RequestResponse = { /** 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; }; /** * 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( requestFn: () => Promise, makeRequestOnMount = false ): RequestResponse { const [data, setData] = useState(); const [loading, setLoading] = useState(false); const [loaded, setLoaded] = useState(false); const [error, setError] = useState(); 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. // oxlint-disable-next-line react-hooks/exhaustive-deps }, []); return { data, loading, loaded, error, request }; }