react-api-adts
Version:
Helpful algebraic data types for API handling in React apps.
44 lines (43 loc) • 1.38 kB
TypeScript
declare type FormState<T> = SuccessState<T> | ErrorState | LoadingState | ReadyState;
interface SuccessState<T> {
kind: "success";
result: T;
}
interface ErrorState {
kind: "error";
msg: string;
}
interface LoadingState {
kind: "loading";
}
interface ReadyState {
kind: "ready";
}
export declare class FormStateHandler<T = unknown> {
readonly isSuccess: boolean;
readonly isError: boolean;
readonly isLoading: boolean;
readonly isReady: boolean;
readonly result: T | undefined;
readonly errorMsg: string | undefined;
readonly state: FormState<T>;
private readonly setState;
private handlers;
constructor(state: FormState<T>, setState: (state: FormState<T>) => void);
match<S>(matchers: {
success?: (t: T) => S;
error?: (msg: string) => S;
ready?: () => S;
loading?: () => S;
}): S | undefined;
success(result: T): void;
error(msg: string): void;
loading(): void;
ready(): void;
handleSuccess(callback: (t: T) => void): void;
handleError(callback: (msg: string) => void): void;
}
export declare type FormResult<T> = SuccessState<T> | ErrorState;
export declare function formResultPromise<T = unknown>(fun: (handler: FormStateHandler<T>) => void): Promise<FormResult<T>>;
export declare function useFormState<T = unknown>(): FormStateHandler<T>;
export {};