Forms
A "new post" form that sends a POST request to dummyjson. The server checks the author: leave it empty and it answers
400, pick an unknown id and it answers 404. Both messages show up next to the field.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { createClient } from "@hyper-fetch/core";
export const client = createClient({ url: "https://dummyjson.com" });
export type NewPost = { title: string; body: string; userId?: number };
export type Post = NewPost & { id: number };
/** The shape dummyjson sends with a 4xx status, for example `{ "message": "User id is required" }`. */
export type ApiError = { message: string };
/**
* `payload` types the `submit({ payload })` call, `error` types `error` for this endpoint.
* dummyjson validates the post on the server and simulates the write, so nothing is saved.
*/
export const createPostRequest = client.createRequest<{
response: Post;
payload: NewPost;
error: ApiError;
}>()({
endpoint: "/posts/add",
method: "POST",
});
npx tiged BetterTyped/hyper-fetch/examples/react/forms hyper-fetch-react-forms && cd hyper-fetch-react-forms && npm install && npm run devuseSubmitsends nothing on mount. The request runs when you callsubmit({ payload }).- Typed payload: the
payloadgeneric makessubmit()reject a body with the wrong shape. submittingdisables the form and marks the button busy while the request is in flight.- Server errors: the
errorgeneric types the JSON body of a failed response, soerror.messageis safe to read. - Lifecycle callbacks:
onSubmitSuccessresets the form andonSubmitErrorexplains the failure.
How it works
-
api.tsdefinescreatePostRequestwithmethod: "POST"and three generics:response,payloadanderror. dummyjson replies to bad input with a 4xx status and{ "message": "..." }, which is whatApiErrordescribes. -
handleSubmitstops the browser's own submit, reads the fields withFormDataand callssubmit({ payload: readPayload(form) }). The default adapter sends the payload as JSON. -
submittingistrueuntil the response arrives. A disabled<fieldset>blocks every input at once. -
A failed request does not throw.
submit()resolves with the response, and the hook storeserrorandstatus. The form readserror.messageand setsaria-invalidon the author field.{error && <small>{error.message}</small>;} -
onSubmitSuccessandonSubmitErrorrun once per finished submission. Put side effects there, such as resetting the form, showing a toast or navigating away.onSubmitSuccess(({ response }) => {setNotice({ ok: true, text: `Created post #${response.data.id}` });formRef.current?.reset();});
dummyjson simulates writes: the post gets an id, but it is not saved.
- Create and edit forms that send data to an API.
- Forms where the server has the final say on validation, such as unique emails or existing ids.
Related
useSubmit turns a typed request into a submit() function with submitting, data and error state. Server
validation errors arrive as typed data in error, and the lifecycle callbacks handle what happens next.
