13 lines · 566 BRaw
| 1 | import { useEffect } from "react"; |
| 2 | |
| 3 | interface FetcherLike<T> { |
| 4 | readonly state: "idle" | "loading" | "submitting"; |
| 5 | readonly data?: T; |
| 6 | } |
| 7 | |
| 8 | /** Runs `onSuccess` once each time the fetcher settles on an answer with no error, such as to close an editor or clear a draft. */ |
| 9 | export function useOnSuccess<T extends { readonly error: string | null }>(fetcher: FetcherLike<T>, onSuccess: (data: T) => void): void { |
| 10 | useEffect(() => { |
| 11 | if (fetcher.state === "idle" && fetcher.data && !fetcher.data.error) onSuccess(fetcher.data); |
| 12 | }, [fetcher.state, fetcher.data]); |
| 13 | } |