UNPKG

remix-conform-rpc

Version:

Supercharge your remix/react-router actions and loaders with typesafe param and query parsing using conform and zod

33 lines (32 loc) 2.21 kB
import { z, ZodSchema } from "zod"; import { type FormEvent } from "react"; import { type ErrorResponse, type InvalidSubmissionResponse } from "../utils/error.js"; import { type DefaultValue } from "@conform-to/react"; import type { Submission } from "@conform-to/dom"; import { type ActionFunction, type FetcherWithComponents } from "react-router"; type ActionReturnType<TAction extends ActionFunction> = Awaited<ReturnType<TAction>>; export type SuccessResponseData<TAction extends ActionFunction, TSchema extends ZodSchema> = Exclude<ActionReturnType<TAction>, InvalidSubmissionResponse<ReturnType<Submission<z.infer<TSchema>>["reply"]>> | ErrorResponse<null>>; interface UseActionOptions<TAction extends ActionFunction, TSchema extends ZodSchema> { path?: string; method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; onSuccess?(response: SuccessResponseData<TAction, TSchema>): void; onError?(response: InvalidSubmissionResponse<ReturnType<Submission<z.infer<TSchema>>["reply"]>> | ErrorResponse<unknown>): void; } declare function useAction<TAction extends ActionFunction, TSchema extends ZodSchema>(options: UseActionOptions<TAction, TSchema>): { submit: (data: z.infer<TSchema>) => void; fetcher: FetcherWithComponents<Awaited<ReturnType<TAction>>>; }; interface UseActionFormOptions<TAction extends ActionFunction, TSchema extends ZodSchema> extends UseActionOptions<TAction, TSchema> { schema: TSchema; onFormSubmit?: (event: FormEvent<HTMLFormElement>, data: z.infer<TSchema>) => void; defaultValue?: DefaultValue<z.infer<TSchema>>; } declare function useActionForm<TAction extends ActionFunction, TSchema extends ZodSchema>(options: UseActionFormOptions<TAction, TSchema> & { schema: TSchema; }): { form: import("@conform-to/react").FormMetadata<z.TypeOf<TSchema>, string[]>; fields: Required<{ [Key in keyof import("@conform-to/dom").Combine<z.TypeOf<TSchema>>]: import("@conform-to/react").FieldMetadata<import("@conform-to/dom").Combine<z.TypeOf<TSchema>>[Key], z.TypeOf<TSchema>, string[]>; }>; fetcher: FetcherWithComponents<Awaited<ReturnType<TAction>>>; submit: (data: z.TypeOf<TSchema>) => void; }; export { useAction, useActionForm };