You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/api/configureStore.mdx
+22-2Lines changed: 22 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -9,8 +9,28 @@ hide_title: true
9
9
10
10
# `configureStore`
11
11
12
-
A friendly abstraction over the standard Redux `createStore` function that adds good defaults
13
-
to the store setup for a better development experience.
12
+
The standard method for creating a Redux store. It uses the low-level Redux core `createStore` method internally, but wraps that to provide good defaults to the store setup for a better development experience.
13
+
14
+
## Purpose and Behavior
15
+
16
+
A standard Redux store setup typically requires multiple pieces of configuration:
17
+
18
+
- Combining the slice reducers into the root reducer
19
+
- Creating the middleware enhancer, usually with the thunk middleware or other side effects middleware, as well as middleware that might be used for development checks
20
+
- Adding the Redux DevTools enhancer, and composing the enhancers together
21
+
- Calling `createStore`
22
+
23
+
Legacy Redux usage patterns typically required several dozen lines of copy-pasted boilerplate to achieve this.
24
+
25
+
Redux Toolkit's `configureStore` simplifies that setup process, by doing all that work for you. One call to `configureStore` will:
26
+
27
+
- Call `combineReducers` to combine your slices reducers into the root reducer function
28
+
- Add the thunk middleware and called `applyMiddleware`
29
+
- In development, automatically add more middleware to check for common mistakes like accidentally mutating the state
30
+
- Automatically set up the Redux DevTools Extension connection
31
+
- Call `createStore` to create a Redux store using that root reducer and those configuration options
32
+
33
+
`configureStore` also offers an improved API and usage patterns compared to the original `createStore` by accepting named fields for `reducer`, `preloadedState`, `middleware`, `enhancers`, and `devtools`, as well as much better TS type inference.
Conceptually, eachslicereducer"owns"itssliceofstate. There's also a natural correspondance between the update logic defined inside `reducers`, and the action types that are generated based on those.
However, unlikethe`reducers`field, eachindividualcasereducerinsideof`extraReducers`will_not_generateanewactiontypeoractioncreator.
148
+
149
+
Iftwofieldsfrom`reducers`and`extraReducers`happentoendupwiththesameactiontypestring, the function from `reducers` will be used to handle that action type.
149
150
150
151
### The`extraReducers`"builder callback"notation
151
152
@@ -162,6 +163,14 @@ See [the "Builder Callback Notation" section of the `createReducer` reference](.
- custom action creator functions that have a `.match` property that is a type guard
39
39
@@ -45,7 +45,7 @@ Accepts the same inputs as `isAllOf` and will return a type guard function that
45
45
46
46
## `isAsyncThunkAction`
47
47
48
-
A higher-order function that returns a type guard function that may be used to check whether an action was created by [`createAsyncThunk`](./createAsyncThunk).
48
+
A higher-order function that returns a type guard function that may be used to check whether an action was created by [`createAsyncThunk`](./createAsyncThunk.mdx).
@@ -117,7 +117,7 @@ function handleRejectedAction(action: AnyAction) {
117
117
118
118
## `isRejectedWithValue`
119
119
120
-
A higher-order function that returns a type guard function that may be used to check whether an action is a 'rejected' action creator from the `createAsyncThunk` promise lifecycle that was created by [`rejectWithValue`](./createAsyncThunk#handling-thunk-errors).
120
+
A higher-order function that returns a type guard function that may be used to check whether an action is a 'rejected' action creator from the `createAsyncThunk` promise lifecycle that was created by [`rejectWithValue`](./createAsyncThunk.mdx#handling-thunk-errors).
@@ -26,6 +26,30 @@ See also [`baseQuery API Reference`](../api/createApi.mdx#basequery).
26
26
27
27
RTK Query expects a `baseQuery` function to be called with three arguments: `args`, `api`, and `extraOptions`. It is expected to return an object with either a `data` or `error` property, or a promise that resolves to return such an object.
28
28
29
+
:::tip
30
+
31
+
Base query and query functions must _always_ catch errors themselves, and return it in an object!
32
+
33
+
```ts no-transpile
34
+
function brokenCustomBaseQuery() {
35
+
// ❌ Don't let this throw by itself
36
+
const data =awaitfetchSomeData()
37
+
return { data }
38
+
}
39
+
40
+
function correctCustomBaseQuery() {
41
+
// ✅ Catch errors and _return_ them so the RTKQ logic can track it
42
+
try {
43
+
const data =awaitfetchSomeData()
44
+
return { data }
45
+
} catch (error) {
46
+
return { error }
47
+
}
48
+
}
49
+
```
50
+
51
+
:::
52
+
29
53
#### baseQuery function arguments
30
54
31
55
```ts title="baseQuery example arguments" no-transpile
@@ -205,7 +229,11 @@ argument, which can be used while determining the transformed response. The valu
205
229
dependent on the `baseQuery` used.
206
230
207
231
```ts title="transformErrorResponse meta example" no-transpile
Individual endpoints on [`createApi`](../api/createApi.mdx) accept a [`queryFn`](../api/createApi.mdx#queryfn) property which allows a given endpoint to ignore `baseQuery` for that endpoint by providing an inline function determining how that query resolves.
259
+
RTK Query comes with `fetchBaseQuery` out of the box, which makes it straightforward to define endpoints that talk to HTTP URLs (such as a typical REST API). We also have integrations with GraphQL as well. However, at its core, RTK Query is really about tracking loading state and cached values for _any_ async request/response sequence, not just HTTP requests.
232
260
233
-
This can be useful for scenarios where you want to have particularly different behaviour for a single endpoint, or where the query itself is not relevant. Such situations may include:
261
+
RTK Query supports defining endpoints that run arbitrary async logic and return a result. Individual endpoints on [`createApi`](../api/createApi.mdx) accept a [`queryFn`](../api/createApi.mdx#queryfn) property, which let you write your own async function with whatever logic you want inside.
262
+
263
+
This can be useful for scenarios where you want to have particularly different behaviour for a single endpoint, or where the query itself is not relevant, including:
234
264
235
265
- One-off queries that use a different base URL
236
266
- One-off queries that use different request handling, such as automatic re-tries
237
267
- One-off queries that use different error handling behaviour
268
+
- Queries that make requests using a third-party library SDK, such as Firebase or Supabase
269
+
- Queries that perform async tasks that are not a typical request/response
238
270
- Performing multiple requests with a single query ([example](#performing-multiple-requests-with-a-single-query))
239
271
- Leveraging invalidation behaviour with no relevant query ([example](#using-a-no-op-queryfn))
240
272
- Using [Streaming Updates](./streaming-updates) with no relevant initial request ([example](#streaming-data-with-no-initial-request))
@@ -243,7 +275,39 @@ See also [`queryFn API Reference`](../api/createApi.mdx#queryfn) for the type si
243
275
244
276
### Implementing a `queryFn`
245
277
246
-
In order to use `queryFn`, it can be treated as an inline `baseQuery`. It will be called with the same arguments as `baseQuery`, as well as the provided `baseQuery` function itself (`arg`, `api`, `extraOptions`, and `baseQuery`). Similarly to `baseQuery`, it is expected to return an object with either a `data` or `error` property, or a promise that resolves to return such an object.
278
+
A `queryFn` can be thought of as an inline `baseQuery`. It will be called with the same arguments as `baseQuery`, as well as the provided `baseQuery` function itself (`arg`, `api`, `extraOptions`, and `baseQuery`). Similarly to `baseQuery`, it is expected to return an object with either a `data` or `error` property, or a promise that resolves to return such an object.
You could also try creating a custom base query that uses the SDK, and define endpoints that pass method names or args into that base query.
968
+
883
969
### Using a no-op queryFn
884
970
885
971
In certain scenarios, you may wish to have a `query` or `mutation` where sending a request or returning data is not relevant for the situation. Such a scenario would be to leverage the `invalidatesTags` property to force re-fetch specific `tags` that have been provided to the cache.
Copy file name to clipboardExpand all lines: docs/rtk-query/usage/mutations.mdx
+3Lines changed: 3 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -24,6 +24,8 @@ If the `query` callback needs additional data to generate the URL, it should be
24
24
25
25
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.
26
26
27
+
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.
28
+
27
29
```ts title="Example of all mutation endpoint options"
28
30
// file: types.ts noEmit
29
31
exportinterfacePost {
@@ -41,6 +43,7 @@ const api = createApi({
41
43
}),
42
44
tagTypes: ['Post'],
43
45
endpoints: (build) => ({
46
+
// The mutation accepts a `Partial<Post>` arg, and returns a `Post`
Copy file name to clipboardExpand all lines: docs/rtk-query/usage/queries.mdx
+4-1Lines changed: 4 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -34,6 +34,8 @@ If the `query` callback needs additional data to generate the URL, it should be
34
34
35
35
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.
36
36
37
+
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.
38
+
37
39
```ts title="Example of all query endpoint options"
38
40
// file: types.ts noEmit
39
41
exportinterfacePost {
@@ -52,8 +54,9 @@ const api = createApi({
52
54
}),
53
55
tagTypes: ['Post'],
54
56
endpoints: (build) => ({
57
+
// highlight-start
58
+
// The query accepts a number and returns a Post
55
59
getPost: build.query<Post, number>({
56
-
// highlight-start
57
60
// note: an optional `queryFn` may be used in place of `query`
58
61
query: (id) => ({ url: `post/${id}` }),
59
62
// Pick out data and prevent nested properties in a hook or selector
0 commit comments