Skip to content

Commit d984e02

Browse files
phryneasmsutkowski
andauthored
update createApi docs (#76)
* update createApi docs * Add danger tag to internalActions Co-authored-by: Matt Sutkowski <[email protected]>
1 parent 1c21902 commit d984e02

File tree

1 file changed

+145
-90
lines changed

1 file changed

+145
-90
lines changed

docs/api/createApi.md

+145-90
Original file line numberDiff line numberDiff line change
@@ -22,92 +22,6 @@ The main point where you will define a service to use in your application.
2222
keepUnusedDataFor?: number;
2323
```
2424

25-
**It returns:**
26-
27-
- [`reducerPath`](#reducerpath)
28-
- [`reducer`](#reducer)
29-
- [`middleware`](#middleware)
30-
- [`endpoints`](#endpoints-returned-by-createapi)
31-
- **[endpointName]**
32-
- [`initiate`](#actions)
33-
- [`select`](#select)
34-
- [`useQuery or useMutation`](#hooks)
35-
- [`internalActions`](#internalactions)
36-
- [`util`](#util)
37-
- [`injectEndpoints`](#injectendpoints)
38-
- [`usePrefetch`](../concepts/prefetching#prefetching-with-react-hooks)
39-
- [`Auto-generated hooks`](#auto-generated-hooks)
40-
41-
```ts title="All returned properties"
42-
const api = createApi({
43-
baseQuery: fetchBaseQuery('/'),
44-
endpoints: (builder) => ({
45-
// ...
46-
}),
47-
});
48-
49-
export const {
50-
reducerPath,
51-
reducer,
52-
middleware,
53-
endpoints,
54-
internalActions,
55-
util,
56-
injectEndpoints,
57-
usePrefetch,
58-
...generatedHooks
59-
} = api;
60-
```
61-
62-
#### middleware
63-
64-
This is a standard redux middleware and is responsible for things like [polling](../concepts/polling), [garbage collection](#keepunuseddatafor) and a handful of other things. Make sure it's [included in your store](../introduction/getting-started#add-the-service-to-your-store).
65-
66-
#### reducer
67-
68-
A standard redux reducer that enables core functionality. Make sure it's [included in your store](../introduction/getting-started#add-the-service-to-your-store).
69-
70-
### `endpoints` returned by `createApi`
71-
72-
#### actions
73-
74-
React Hooks users will most likely never need to use these in most cases. These are redux action creators that you can `dispatch` with `useDispatch` or `store.dispatch()`.
75-
76-
:::note Usage of actions outside of React Hooks
77-
When dispatching an action creator, you're responsible for storing a reference to the promise it returns in the event that you want to update that specific subscription. To get an idea of what that entails, see the [Svelte Example](../examples/svelte) or the [React Class Components Example](../examples/react-class-components)
78-
:::
79-
80-
#### select
81-
82-
`select` is how you access your `query` or `mutation` data from the cache. If you're using Hooks, you don't have to worry about this in most cases. There are several ways to use them:
83-
84-
```js title="React Hooks"
85-
const { data, status } = useSelector(api.getPosts.select());
86-
```
87-
88-
```js title="Using connect from react-redux"
89-
const mapStateToProps = (state) => ({
90-
data: api.getPosts.select()(state),
91-
});
92-
connect(null, mapStateToProps);
93-
```
94-
95-
```js title="Svelte"
96-
$: ({ data, status } = api.getPosts.select()($store));
97-
```
98-
99-
#### hooks
100-
101-
Hooks are specifically for React Hooks users. Under each `api.endpoint.[endpointName]`, you will have `useQuery` or `useMutation` depending on the type. For example, if you had `getPosts` and `updatePost`, these options would be available:
102-
103-
```ts title="Hooks usage"
104-
const { data } = api.endpoints.getPosts.useQuery();
105-
const { data } = api.endpoints.updatePost.useMutation();
106-
107-
const { data } = api.useGetPostsQuery();
108-
const [updatePost] = api.useUpdatePostMutation();
109-
```
110-
11125
### `baseQuery`
11226

11327
```ts title="Simulating axios-like interceptors with a custom base query"
@@ -161,12 +75,13 @@ const apiTwo = createApi({
16175

16276
### `serializeQueryArgs`
16377

164-
Accepts a custom function if you have a need to change the serialization behavior for any reason. Defaults to:
78+
Accepts a custom function if you have a need to change the creation of cache keys for any reason. Defaults to:
16579

16680
```ts no-compile
167-
function defaultSerializeQueryArgs(args: any, endpoint: string) {
168-
return `${endpoint}/${JSON.stringify(args)}`;
169-
}
81+
export const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({ endpoint, queryArgs }) => {
82+
// Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })
83+
return `${endpoint}(${JSON.stringify(queryArgs, Object.keys(queryArgs || {}).sort())})`;
84+
};
17085
```
17186

17287
### `endpoints`
@@ -198,9 +113,18 @@ Endpoints are just a set of operations that you want to perform against your ser
198113
2. `[{ type: 'Post' }]` - equivalent to 1
199114
3. `[{ type: 'Post', id: 1 }]`
200115
- `invalidates` _(optional)_
116+
201117
- Used by `mutations` for [cache invalidation](../concepts/mutations#advanced-mutations-with-revalidation) purposes.
202118
- Expects the same shapes as `provides`
203119

120+
- `onStart`, `onError` and `onSuccess` _(optional)_
121+
- Can be used in `mutations` for [optimistic updates](../concepts/optimistic-updates).
122+
- ```ts title="signatures"
123+
function onStart(arg: QueryArg, mutationApi: MutationApi<ReducerPath, Context>): void;
124+
function onError(arg: QueryArg, mutationApi: MutationApi<ReducerPath, Context>, error: unknown): void;
125+
function onSuccess(arg: QueryArg, mutationApi: MutationApi<ReducerPath, Context>, result: ResultType): void;
126+
```
127+
204128
#### How endpoints get used
205129

206130
When defining a key like `getPosts` as shown below, it's important to know that this name will become exportable from `api` and be able to referenced under `api.endpoints.getPosts.useQuery()`, `api.endpoints.getPosts.initiate()` and `api.endpoints.getPosts.select()`. The same thing applies to `mutation`s but they reference `useMutation` instead of `useQuery`.
@@ -279,6 +203,102 @@ export const api = createApi({
279203
});
280204
```
281205
206+
## Return value
207+
208+
- [`reducerPath`](#reducerpath)
209+
- [`reducer`](#reducer)
210+
- [`middleware`](#middleware)
211+
- [`endpoints`](#endpoints-returned-by-createapi)
212+
- **[endpointName]**
213+
- [`initiate`](#initiate)
214+
- [`select`](#select)
215+
- [`useQuery or useMutation`](#hooks)
216+
- [`internalActions`](#internalactions)
217+
- [`util`](#util)
218+
- [`injectEndpoints`](#injectendpoints)
219+
- [`usePrefetch`](../concepts/prefetching#prefetching-with-react-hooks)
220+
- [`Auto-generated hooks`](#auto-generated-hooks)
221+
222+
```ts title="All returned properties"
223+
const api = createApi({
224+
baseQuery: fetchBaseQuery('/'),
225+
endpoints: (builder) => ({
226+
// ...
227+
}),
228+
});
229+
230+
export const {
231+
reducerPath,
232+
reducer,
233+
middleware,
234+
endpoints,
235+
internalActions,
236+
util,
237+
injectEndpoints,
238+
usePrefetch,
239+
...generatedHooks
240+
} = api;
241+
```
242+
243+
#### middleware
244+
245+
This is a standard redux middleware and is responsible for things like [polling](../concepts/polling), [garbage collection](#keepunuseddatafor) and a handful of other things. Make sure it's [included in your store](../introduction/getting-started#add-the-service-to-your-store).
246+
247+
#### reducer
248+
249+
A standard redux reducer that enables core functionality. Make sure it's [included in your store](../introduction/getting-started#add-the-service-to-your-store).
250+
251+
### `endpoints` returned by `createApi`
252+
253+
#### initiate
254+
255+
React Hooks users will most likely never need to use these in most cases. These are redux action creators that you can `dispatch` with `useDispatch` or `store.dispatch()`.
256+
257+
:::note Usage of actions outside of React Hooks
258+
When dispatching an action creator, you're responsible for storing a reference to the promise it returns in the event that you want to update that specific subscription. Also, you have to manually unsubscribe once your component unmounts. To get an idea of what that entails, see the [Svelte Example](../examples/svelte) or the [React Class Components Example](../examples/react-class-components)
259+
:::
260+
261+
#### select
262+
263+
`select` is how you access your `query` or `mutation` data from the cache. If you're using Hooks, you don't have to worry about this in most cases. There are several ways to use them:
264+
265+
```js title="React Hooks"
266+
const { data, status } = useSelector(api.getPosts.select());
267+
```
268+
269+
```js title="Using connect from react-redux"
270+
const mapStateToProps = (state) => ({
271+
data: api.getPosts.select()(state),
272+
});
273+
connect(null, mapStateToProps);
274+
```
275+
276+
```js title="Svelte"
277+
$: ({ data, status } = api.getPosts.select()($store));
278+
```
279+
280+
#### hooks
281+
282+
Hooks are specifically for React Hooks users. Under each `api.endpoint.[endpointName]`, you will have `useQuery` or `useMutation` depending on the type. For example, if you had `getPosts` and `updatePost`, these options would be available:
283+
284+
```ts title="Hooks usage"
285+
const { data } = api.endpoints.getPosts.useQuery();
286+
const { data } = api.endpoints.updatePost.useMutation();
287+
288+
const { data } = api.useGetPostsQuery();
289+
const [updatePost] = api.useUpdatePostMutation();
290+
```
291+
292+
#### action matchers
293+
294+
These are action matchers for each endpoint to allow you matching on redux actions for that endpoint - for example in slice `extraReducers` or a custom middleware. Those are implemented as follows:
295+
296+
```ts
297+
matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpoint)),
298+
matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpoint)),
299+
matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpoint)),
300+
```
301+
282302
### Auto-generated Hooks
283303

284304
React users are able to take advantage of auto-generated hooks. By default, `createApi` will automatically generate type-safe hooks (TS 4.1+ only) for you based on the name of your endpoints. The general format is `use(Endpointname)(Query|Mutation)` - `use` is prefixed, the first letter of your endpoint name is capitalized, then `Query` or `Mutation` is appended depending on the type.
@@ -306,10 +326,45 @@ export { useGetPostsQuery, useAddPostMutation } = api;
306326

307327
### `internalActions`
308328

329+
:::danger
330+
These may change at any given time and are not part of the public API for now
331+
:::
332+
333+
- `updateSubscriptionOptions: ActionCreatorWithPayload<{ endpoint: string; requestId: string; options: SubscriptionOptions; queryCacheKey: QueryCacheKey }, string>;`
334+
- `queryResultPatched: ActionCreatorWithPayload<{ queryCacheKey: QueryCacheKey, patches: Patch[]; }, string>`
335+
- `removeQueryResult: ActionCreatorWithPayload<{ queryCacheKey: QueryCacheKey }, string>`
336+
- `unsubscribeQueryResult: ActionCreatorWithPayload<{ queryCacheKey: QueryCacheKey, requestId: string }, string>`,
337+
- `unsubscribeMutationResult: ActionCreatorWithPayload<MutationSubstateIdentifier, string>`,
338+
- `prefetchThunk(endpointName, args, options: PrefetchOptions) => ThunkAction<void, any, any, AnyAction>`
339+
309340
### `util`
310341

342+
Both of these utils are currently used for [optimistic updates](../concepts/optimistic-updates).
343+
344+
- **patchQueryResult**
345+
346+
```ts
347+
<EndpointName extends QueryKeys<Definitions>>(
348+
endpointName: EndpointName,
349+
args: QueryArgFrom<Definitions[EndpointName]>,
350+
patches: Patch[]
351+
) => ThunkAction<void, PartialState, any, AnyAction>
352+
```
353+
354+
- **updateQueryResult**
355+
356+
```ts
357+
<EndpointName extends QueryKeys<Definitions>>(
358+
endpointName: EndpointName,
359+
args: QueryArgFrom<Definitions[EndpointName]>,
360+
updateRecicpe: Recipe<ResultTypeFrom<Definitions[EndpointName]>>
361+
) => ThunkAction<PatchCollection, PartialState, any, AnyAction>
362+
```
363+
311364
### `injectEndpoints`
312365

366+
See [Code Splitting](../concepts/code-splitting)
367+
313368
### `keepUnusedDataFor`
314369

315370
Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.

0 commit comments

Comments
 (0)