Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Clarify TS generics for queries and mutations
  • Loading branch information
markerikson committed Sep 23, 2023
commit f2ecd039b08a5104fd41ac2a68be9abe3f890840
3 changes: 3 additions & 0 deletions docs/rtk-query/usage/mutations.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ If the `query` callback needs additional data to generate the URL, it should be

Mutation endpoints may also modify the response contents before the result is cached, define "tags" to identify cache invalidation, and provide cache entry lifecycle callbacks to run additional logic as cache entries are added and removed.

When used with TypeScript, you should supply generics for the return type and the expected query argument: `build.mutation<ReturnType, ArgType>`. If there is no argument, use `void` for the arg type instead.

```ts title="Example of all mutation endpoint options"
// file: types.ts noEmit
export interface Post {
Expand All @@ -41,6 +43,7 @@ const api = createApi({
}),
tagTypes: ['Post'],
endpoints: (build) => ({
// The mutation accepts a `Partial<Post>` arg, and returns a `Post`
updatePost: build.mutation<Post, Partial<Post> & Pick<Post, 'id'>>({
// highlight-start
// note: an optional `queryFn` may be used in place of `query`
Expand Down
5 changes: 4 additions & 1 deletion docs/rtk-query/usage/queries.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ If the `query` callback needs additional data to generate the URL, it should be

Query endpoints may also modify the response contents before the result is cached, define "tags" to identify cache invalidation, and provide cache entry lifecycle callbacks to run additional logic as cache entries are added and removed.

When used with TypeScript, you should supply generics for the return type and the expected query argument: `build.query<ReturnType, ArgType>`. If there is no argument, use `void` for the arg type instead.

```ts title="Example of all query endpoint options"
// file: types.ts noEmit
export interface Post {
Expand All @@ -52,8 +54,9 @@ const api = createApi({
}),
tagTypes: ['Post'],
endpoints: (build) => ({
// highlight-start
// The query accepts a number and returns a Post
getPost: build.query<Post, number>({
// highlight-start
// note: an optional `queryFn` may be used in place of `query`
query: (id) => ({ url: `post/${id}` }),
// Pick out data and prevent nested properties in a hook or selector
Expand Down