Skip to content

Commit 6a6b195

Browse files
authored
Merge pull request #1081 from Shrugsy/docs/extend-customizing-queries-content
2 parents d9ae665 + b832b3a commit 6a6b195

File tree

6 files changed

+649
-229
lines changed

6 files changed

+649
-229
lines changed

docs/package-lock.json

Lines changed: 79 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docs/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
"@types/redux-logger": "^3.0.8",
99
"axios": "^0.20.0",
1010
"formik": "^2.1.5",
11+
"graphql-request": "^3.4.0",
1112
"immutable": "^3.8.2",
1213
"rxjs": "^6.6.2"
1314
}

docs/rtk-query/api/createApi.mdx

Lines changed: 82 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,49 @@ export const { useGetPokemonByNameQuery } = pokemonApi
5858

5959
[summary](docblock://query/createApi.ts?token=CreateApiOptions.baseQuery)
6060

61+
#### baseQuery function arguments
62+
63+
- `args` - The return value of the `query` function for a given endpoint
64+
- `api` - The `BaseQueryApi` object, containing `signal`, `dispatch` and `getState` properties
65+
- `signal` - An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) object that may be used to abort DOM requests and/or read whether the request is aborted.
66+
- `dispatch` - The `store.dispatch` method for the corresponding Redux store
67+
- `getState` - A function that may be called to access the current store state
68+
- `extraOptions` - The value of the optional `extraOptions` property provided for a given endpoint
69+
70+
#### baseQuery function signature
71+
72+
```ts title="Base Query signature" no-transpile
73+
export type BaseQueryFn<
74+
Args = any,
75+
Result = unknown,
76+
Error = unknown,
77+
DefinitionExtraOptions = {},
78+
Meta = {}
79+
> = (
80+
args: Args,
81+
api: BaseQueryApi,
82+
extraOptions: DefinitionExtraOptions
83+
) => MaybePromise<QueryReturnValue<Result, Error, Meta>>
84+
85+
export interface BaseQueryApi {
86+
signal: AbortSignal
87+
dispatch: ThunkDispatch<any, any, any>
88+
getState: () => unknown
89+
}
90+
91+
export type QueryReturnValue<T = unknown, E = unknown, M = unknown> =
92+
| {
93+
error: E
94+
data?: undefined
95+
meta?: M
96+
}
97+
| {
98+
error?: undefined
99+
data: T
100+
meta?: M
101+
}
102+
```
103+
61104
[examples](docblock://query/createApi.ts?token=CreateApiOptions.baseQuery)
62105
63106
### `endpoints`
@@ -300,83 +343,58 @@ _(required if no `query` provided)_
300343

301344
[summary](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQueryFn.queryFn)
302345

303-
[examples](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQueryFn.queryFn)
346+
Called with the same arguments as `baseQuery`, as well as the provided `baseQuery` function itself. It is expected to return an object with either a `data` or `error` property, or a promise that resolves to return such an object.
304347

305-
### `transformResponse`
306-
307-
_(optional, can't be used with `queryFn`)_
308-
309-
[summary](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.transformResponse)
348+
See also [Customizing queries with queryFn](../usage/customizing-queries.mdx#customizing-queries-with-queryfn).
310349

311-
In some cases, you may want to manipulate the data returned from a query before you put it in the cache. In this instance, you can take advantage of `transformResponse`.
312-
313-
By default, the payload from the server is returned directly.
314-
315-
```ts
316-
function defaultTransformResponse(baseQueryReturnValue: unknown) {
317-
return baseQueryReturnValue
350+
```ts title="queryFn signature" no-transpile
351+
queryFn(
352+
arg: QueryArg,
353+
api: BaseQueryApi,
354+
extraOptions: BaseQueryExtraOptions<BaseQuery>,
355+
baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>
356+
): MaybePromise<
357+
| {
358+
error: BaseQueryError<BaseQuery>
359+
data?: undefined
360+
}
361+
| {
362+
error?: undefined
363+
data: ResultType
364+
}
365+
>
366+
367+
export interface BaseQueryApi {
368+
signal: AbortSignal
369+
dispatch: ThunkDispatch<any, any, any>
370+
getState: () => unknown
318371
}
319372
```
320373

321-
To change it, provide a function that looks like:
374+
#### queryFn function arguments
322375

323-
```ts title="Unpack a deeply nested collection" no-transpile
324-
transformResponse: (response) => response.some.deeply.nested.collection
325-
```
376+
- `args` - The argument provided when the query itself is called
377+
- `api` - The `BaseQueryApi` object, containing `signal`, `dispatch` and `getState` properties
378+
- `signal` - An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) object that may be used to abort DOM requests and/or read whether the request is aborted.
379+
- `dispatch` - The `store.dispatch` method for the corresponding Redux store
380+
- `getState` - A function that may be called to access the current store state
381+
- `extraOptions` - The value of the optional `extraOptions` property provided for the endpoint
382+
- `baseQuery` - The `baseQuery` function provided to the api itself
326383

327-
#### Example - Normalizing response data
384+
[examples](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQueryFn.queryFn)
328385

329-
```ts title="Normalize the response data" no-transpile
330-
transformResponse: (response) =>
331-
response.reduce((acc, curr) => {
332-
acc[curr.id] = curr
333-
return acc
334-
}, {})
335-
```
386+
### `transformResponse`
336387

337-
#### Example - Unpacking deeply nested data
388+
_(optional, not applicable with `queryFn`)_
338389

339-
```ts title="GraphQL transformation example"
340-
// file: graphqlBaseQuery.ts noEmit
341-
import { BaseQueryFn } from '@reduxjs/toolkit/query'
342-
declare const graphqlBaseQuery: (args: { baseUrl: string }) => BaseQueryFn
343-
declare const gql: (literals: TemplateStringsArray) => void
344-
export { graphqlBaseQuery, gql }
390+
[summary](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.transformResponse)
345391

346-
// file: graphqlApi.ts
347-
import { createApi } from '@reduxjs/toolkit/query'
348-
import { graphqlBaseQuery, gql } from './graphqlBaseQuery'
392+
In some cases, you may want to manipulate the data returned from a query before you put it in the cache. In this instance, you can take advantage of `transformResponse`.
349393

350-
interface Post {
351-
id: number
352-
title: string
353-
}
394+
See also [Customizing query responses with `transformResponse`](../usage/customizing-queries.mdx#customizing-query-responses-with-transformresponse)
354395

355-
export const api = createApi({
356-
baseQuery: graphqlBaseQuery({
357-
baseUrl: '/graphql',
358-
}),
359-
endpoints: (builder) => ({
360-
getPosts: builder.query<Post[], void>({
361-
query: () => ({
362-
body: gql`
363-
query {
364-
posts {
365-
data {
366-
id
367-
title
368-
}
369-
}
370-
}
371-
`,
372-
}),
373-
// highlight-start
374-
transformResponse: (response: { posts: { data: Post[] } }) =>
375-
response.posts.data,
376-
// highlight-end
377-
}),
378-
}),
379-
})
396+
```ts title="Unpack a deeply nested collection" no-transpile
397+
transformResponse: (response) => response.some.deeply.nested.collection
380398
```
381399

382400
### `extraOptions`

docs/rtk-query/usage/cached-data.mdx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1010,8 +1010,8 @@ The Redux docs have always recommended [keeping data in a normalized lookup tabl
10101010

10111011
There are a couple additional points that can help here:
10121012

1013-
- The generated query hooks have [a `selectFromResult` option](../api/created-api/hooks.mdx) that allow components to read individual pieces of data from a query result. As an example, a `<TodoList>` component might call `useTodosQuery()`, and each individual `<TodoListItem>` could use the same query hook but select from the result to get the right todo object.
1014-
- You can use the [`transformResponse` endpoint option](../api/createApi.mdx) to modify the fetched data so that it's stored in a different shape, such as using `createEntityAdapter` to normalize the data _for this one response_ before it's inserted into the cache.
1013+
- The generated query hooks have [a `selectFromResult` option](../api/created-api/hooks.mdx#selectfromresult) that allow components to read individual pieces of data from a query result. As an example, a `<TodoList>` component might call `useTodosQuery()`, and each individual `<TodoListItem>` could use the same query hook but select from the result to get the right todo object.
1014+
- You can use the [`transformResponse` endpoint option](../api/createApi.mdx#transformresponse) to modify the fetched data so that it's [stored in a different shape](./customizing-queries.mdx#customizing-query-responses-with-transformresponse), such as using `createEntityAdapter` to normalize the data _for this one response_ before it's inserted into the cache.
10151015

10161016
## Further information
10171017

0 commit comments

Comments
 (0)