Skip to content

Commit b868b43

Browse files
Add prepare callback usage to createSlice.md (#231)
* Add prepare callback usage to createSlice.md Added a description of the usage of a prepare callback to the createSlice API reference page. Also adapted the multiply case reducer in the example to demonstrate the usage. * Reformatted changes in example * Replace absolute link with a relative one Co-Authored-By: Mark Erikson <mark@isquaredsoftware.com>
1 parent 833313d commit b868b43

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

docs/api/createSlice.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ to force the TS compiler to accept the computed property.)
8282
Each function defined in the `reducers` argument will have a corresponding action creator generated using [`createAction`](./createAction.md)
8383
and included in the result's `actions` field using the same function name.
8484

85+
If you need to customize the creation of the payload value of an action creator by means of a [`prepare callback`](./createAction.md#using-prepare-callbacks-to-customize-action-contents), the value of the appropriate field of the `reducers` argument object should be an object instead of a function. This object must contain two properties: reducer and prepare. The value of the reducer field should be the case reducer function while the value of the prepare field should be the prepare callback function.
86+
8587
The generated `reducer` function is suitable for passing to the Redux `combineReducers` function as a "slice reducer".
8688

8789
You may want to consider destructuring the action creators and exporting them individually, for ease of searching
@@ -109,7 +111,10 @@ const counter = createSlice({
109111
reducers: {
110112
increment: state => state + 1,
111113
decrement: state => state - 1,
112-
multiply: (state, action) => state * action.payload
114+
multiply: {
115+
reducer: (state, action) => state * action.payload,
116+
prepare: value => ({ payload: value || 2 }) // fallback if the payload is a falsy value
117+
}
113118
}
114119
})
115120
@@ -141,6 +146,8 @@ store.dispatch(counter.actions.increment())
141146
// -> { counter: 2, user: {name: '', age: 22} }
142147
store.dispatch(counter.actions.multiply(3))
143148
// -> { counter: 6, user: {name: '', age: 22} }
149+
store.dispatch(counter.actions.multiply())
150+
// -> { counter: 12, user: {name: '', age: 22} }
144151
console.log(`${counter.actions.decrement}`)
145152
// -> "counter/decrement"
146153
store.dispatch(user.actions.setUserName('eric'))

0 commit comments

Comments
 (0)