Optional
extraA callback that receives a builder object to define
case reducers via calls to builder.addCase(actionCreatorOrType, reducer)
.
import { createAction, createSlice, Action } from '@reduxjs/toolkit'
const incrementBy = createAction<number>('incrementBy')
const decrement = createAction('decrement')
interface RejectedAction extends Action {
error: Error
}
function isRejectedAction(action: Action): action is RejectedAction {
return action.type.endsWith('rejected')
}
createSlice({
name: 'counter',
initialState: 0,
reducers: {},
extraReducers: builder => {
builder
.addCase(incrementBy, (state, action) => {
// action is inferred correctly here if using TS
})
// You can chain calls, or have separate `builder.addCase()` lines each time
.addCase(decrement, (state, action) => {})
// You can match a range of action types
.addMatcher(
isRejectedAction,
// `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
(state, action) => {}
)
// and provide a default case if no other handlers matched
.addDefaultCase((state, action) => {})
}
})
The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with undefined
as its state value, and is primarily useful for cases like reading initial state from localStorage
.
The slice's name. Used to namespace the generated action types.
Optional
reducerThe slice's reducer path. Used when injecting into a combined slice reducer.
A mapping from action types to action-type-specific case reducer
functions. For every action type, a matching action creator will be
generated using createAction()
.
Optional
selectorsA map of selectors that receive the slice's state and any additional arguments, and return a result.
Options for
createSlice()
.