import { useEffect, useState } from "react"; import { Failure, Pending, Success, type AsyncOp } from "./async-op.ts"; import { caughtValueToString } from "./caught-value.ts"; /** * Checks if the provided value is non-nullish, otherwise calls provided * getValue function to obtain the value (presumably from some remote location). */ export function useEnsureValue( value: T | null | undefined, getValue: () => Promise | Failure>, ) { const [result, setShareLink] = useState>( value != null ? new Success(value) : new Pending(), ); useEffect(() => { if (value == null) { getValue().then( (success) => { setShareLink(success); }, (error: unknown) => { setShareLink(new Failure(caughtValueToString(error))); }, ); } }, [value, getValue]); return result; }