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/createAction.md
+37-1Lines changed: 37 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -10,7 +10,7 @@ hide_title: true
10
10
A helper function for defining a Redux [action](https://redux.js.org/basics/actions) type and creator.
11
11
12
12
```js
13
-
functioncreateAction(type)
13
+
functioncreateAction(type, prepareAction?)
14
14
```
15
15
16
16
The usual way to define an action in Redux is to separately declare an _action type_ constant and an _action creator_ function for constructing actions of that type.
@@ -47,6 +47,42 @@ console.log(`The action type is: ${increment}`)
47
47
// 'The action type is: counter/increment'
48
48
```
49
49
50
+
## Using Prepare Callbacks to Customize Action Contents
51
+
52
+
By default, the generated action creators accept a single argument, which becomes `action.payload`. This requires the caller to construct the entire payload correctly and pass it in.
53
+
54
+
In many cases, you may want to write additional logic to customize the creation of the `payload` value, such as accepting multiple parameters for the action creator, generating a random ID, or getting the current timestamp. To do this, `createAction` accepts an optional second argument: a "prepare callback" that will be used to construct the payload value.
If provided, all arguments from the action creator will be passed to the prepare callback, and it should return an object with the `payload` field (otherwise the payload of created actions will be `undefined`). Additionally, the object can have a `meta` field that will also be added to created actions. This may contain extra information about the action. These two fields (`payload` and `meta`) adhere to the specification of [Flux Standard Actions](https://github.com/redux-utilities/flux-standard-action#actions).
83
+
84
+
**Note:** The type field will be added automatically.
85
+
50
86
## Usage with createReducer()
51
87
52
88
Because of their `toString()` override, action creators returned by `createAction()` can be used directly as keys for the case reducers passed to [createReducer()](createReducer.md).
0 commit comments