-
-
Notifications
You must be signed in to change notification settings - Fork 612
feat(swr-openapi): useSWRMutation wrapper #2367 #2552
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
prescottprue
wants to merge
4
commits into
openapi-ts:main
Choose a base branch
from
prescottprue:swr-openapi-mutation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| --- | ||
| title: useMutation | ||
| --- | ||
|
|
||
| # {{ $frontmatter.title }} | ||
|
|
||
| `useMutation` is a wrapper around SWR's [useSWRMutation][swr-use-mutation] function. It provides a type-safe hook for remote mutations. | ||
|
|
||
| ```tsx | ||
| import createClient from "openapi-fetch"; | ||
| import type { paths } from "./my-openapi-3-schema"; // generated types | ||
|
|
||
| const client = createClient<paths>({ baseUrl: "https://my-api.com" }); | ||
| const useMutation = createMutationHook(client, "my-api"); | ||
|
|
||
| function MyComponent() { | ||
| const { trigger, data, isMutating } = useMutation("/users/{userId}", "post", { | ||
| params: { | ||
| userId: "123", | ||
| }, | ||
| }); | ||
|
|
||
| return ( | ||
| <button | ||
| disabled={isMutating} | ||
| onClick={() => { | ||
| trigger({ body: { name: "New User Name" } }); | ||
| }} | ||
| > | ||
| Update User Name | ||
| </button> | ||
| ); | ||
| } | ||
| ``` | ||
|
|
||
| ## API | ||
|
|
||
| ### Parameters | ||
|
|
||
| - `key`: | ||
| - `path`: Any endpoint that supports `GET` requests. | ||
| - `init`: (_optional_) Partial fetch options for the chosen endpoint. | ||
| - `method`: HTTP method for the chosen endpoint. | ||
| - `options`: (_optional_) [SWR mutate options][swr-use-mutation-params]. | ||
|
|
||
| ### Returns | ||
|
|
||
| - Return of a [useSWRMutation][swr-mutation-response] including: | ||
|
|
||
| `data`: data for the given key returned from fetcher | ||
| `error`: error thrown by fetcher (or undefined) | ||
| `trigger(arg, options)`: a function to trigger a remote mutation | ||
| `reset`: a function to reset the state (data, error, isMutating) | ||
| `isMutating`: if there's an ongoing remote mutation | ||
|
|
||
| ## How It Works | ||
|
|
||
| ```ts | ||
| function useMutation( | ||
| path, | ||
| method, | ||
| config, | ||
| ) { | ||
| const key = [prefix, path, method]; | ||
|
|
||
| return useSWRMutation( | ||
| key, | ||
| async (_key, { arg }) => { | ||
| const m = method.toUpperCase(); | ||
|
|
||
| const res = await client[m](path, arg); | ||
| if (res.error) { | ||
| throw res.error; | ||
| } | ||
| return res.data; | ||
| }, | ||
| config, | ||
| ); | ||
| }; | ||
|
|
||
| ``` | ||
|
|
||
| [swr-mutate-params]: https://swr.vercel.app/docs/mutation#parameters | ||
| [swr-use-mutation]: https://swr.vercel.app/docs/mutation#useswrmutation | ||
| [swr-use-mutation-params]: https://swr.vercel.app/docs/mutation#useswrmutation-parameters | ||
| [swr-mutation-response]: https://swr.vercel.app/docs/mutation#useswrmutation-return-values |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| export * from "./immutable.js"; | ||
| export * from "./infinite.js"; | ||
| export * from "./mutate.js"; | ||
| export * from "./mutation.js"; | ||
| export * from "./query.js"; | ||
| export * from "./types.js"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import type { Client } from "openapi-fetch"; | ||
| import type { HttpMethod, MediaType, PathsWithMethod } from "openapi-typescript-helpers"; | ||
| import useSWRMutation, { type SWRMutationConfiguration, type SWRMutationResponse } from "swr/mutation"; | ||
| import type { TypesForRequest } from "./types.js"; | ||
| import { useMemo } from "react"; | ||
|
|
||
| /** | ||
| * Produces a typed wrapper for [`useSWRMutation`](https://swr.vercel.app/docs/mutation). | ||
| * | ||
| * ```ts | ||
| * import createClient from "openapi-fetch"; | ||
| * import type { paths } from "./my-openapi-3-schema"; // generated types | ||
| * | ||
| * const client = createClient<paths>({ baseUrl: "https://my-api.com" }); | ||
| * const useMutation = createMutationHook(client, "my-api"); | ||
| * | ||
| * function MyComponent() { | ||
| * const { trigger, data, isMutating } = useMutation("/users", "post"); | ||
| * | ||
| * return ( | ||
| * <button | ||
| * disabled={isMutating} | ||
| * onClick={() => { | ||
| * trigger({ body: { name: "New User" } }); | ||
| * }} | ||
| * > | ||
| * Create User | ||
| * </button> | ||
| * ); | ||
| * } | ||
| * ``` | ||
| */ | ||
| export function createMutationHook<Paths extends {}, IMediaType extends MediaType>( | ||
| client: Client<Paths, IMediaType>, | ||
| prefix: string, | ||
| ) { | ||
| return function useMutation< | ||
| Method extends Extract<HttpMethod, keyof Paths[keyof Paths]>, | ||
| Path extends PathsWithMethod<Paths, Method>, | ||
| T extends TypesForRequest<Paths, Method, Path> = TypesForRequest<Paths, Method, Path>, | ||
| Data = T["Data"], | ||
| Error = T["Error"], | ||
| Init = T["Init"], | ||
| >( | ||
| path: Path, | ||
| method: Method, | ||
| init: Init | null, | ||
| config?: SWRMutationConfiguration<Data, Error, readonly [string, Path, Init], Init>, | ||
| ): SWRMutationResponse<Data, Error, readonly [string, Path, Init], Init> { | ||
| const key = useMemo(() => (init !== null ? ([prefix, path, init] as const) : null), [prefix, path, init]); | ||
|
|
||
| return useSWRMutation( | ||
| key, | ||
| async (_key, { arg }) => { | ||
| const m = method.toUpperCase() as Uppercase<Method>; | ||
|
|
||
| const res = await (client as any)[m](path, arg); | ||
| if (res.error) { | ||
| throw res.error; | ||
| } | ||
| return res.data; | ||
| }, | ||
| config, | ||
| ); | ||
| }; | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wasn't sure if this and the version bump were meant to be done manually or if there is an automated process - I just saw the CI message about the changelog not being updated so I did it manually