@reduxjs/toolkit
- Version 1.9.7
- Published
- 13 MB
- 4 dependencies
- MIT license
Install
npm i @reduxjs/toolkit
yarn add @reduxjs/toolkit
pnpm add @reduxjs/toolkit
Overview
The official, opinionated, batteries-included toolset for efficient Redux development
Index
Variables
Functions
- autoBatchEnhancer()
- configureStore()
- createAction()
- createActionCreatorInvariantMiddleware()
- createEntityAdapter()
- createImmutableStateInvariantMiddleware()
- createListenerMiddleware()
- createReducer()
- createSerializableStateInvariantMiddleware()
- createSlice()
- findNonSerializableValue()
- getDefaultMiddleware()
- getType()
- isAction()
- isActionCreator()
- isAllOf()
- isAnyOf()
- isAsyncThunkAction()
- isFluxStandardAction()
- isFulfilled()
- isImmutableDefault()
- isPending()
- isPlain()
- isPlainObject()
- isRejected()
- isRejectedWithValue()
- miniSerializeError()
- nanoid()
- prepareAutoBatched()
- unwrapResult()
Classes
Interfaces
Type Aliases
- ActionMatchingAllOf
- ActionMatchingAnyOf
- Actions
- AsyncThunk
- AsyncThunkAction
- AsyncThunkOptions
- AsyncThunkPayloadCreator
- AsyncThunkPayloadCreatorReturnValue
- AutoBatchOptions
- CaseReducer
- CaseReducerActions
- CaseReducers
- CaseReducerWithPrepare
- Comparer
- ConfigureEnhancersCallback
- EnhancedStore
- EntityId
- ForkedTaskExecutor
- IdSelector
- ListenerEffect
- ListenerMiddleware
- PayloadAction
- PayloadActionCreator
- PrepareAction
- SliceActionCreator
- SliceCaseReducers
- TaskCancelled
- TaskRejected
- TaskResolved
- TaskResult
- TSHelpersExtractDispatchExtensions
- TypedAddListener
- TypedRemoveListener
- TypedStartListening
- TypedStopListening
- UnsubscribeListener
- Update
- ValidateSliceCaseReducers
Variables
variable addListener
const addListener: BaseActionCreator< ListenerEntry<unknown, ThunkDispatch<unknown, unknown, AnyAction>>, 'listenerMiddleware/add', never, never> & AddListenerOverloads< { payload: ListenerEntry< unknown, ThunkDispatch<unknown, unknown, AnyAction> >; type: 'listenerMiddleware/add'; }, unknown, ThunkDispatch<unknown, unknown, AnyAction>, unknown, unknown >;
Modifiers
@public
variable clearAllListeners
const clearAllListeners: ActionCreatorWithoutPayload<string>;
Modifiers
@public
variable createAsyncThunk
const createAsyncThunk: CreateAsyncThunk<AsyncThunkConfig>;
variable createDraftSafeSelector
const createDraftSafeSelector: any;
"Draft-Safe" version of
reselect
'screateSelector
: If animmer
-drafted object is passed into the resulting selector's first argument, the selector will act on the current draft value, instead of returning a cached value that might be possibly outdated if the draft has been modified since.Modifiers
@public
variable removeListener
const removeListener: BaseActionCreator< ListenerEntry<unknown, ThunkDispatch<unknown, unknown, AnyAction>>, 'listenerMiddleware/remove', never, never> & AddListenerOverloads< { payload: ListenerEntry< unknown, ThunkDispatch<unknown, unknown, AnyAction> >; type: 'listenerMiddleware/remove'; }, unknown, ThunkDispatch<unknown, unknown, AnyAction>, any, UnsubscribeListenerOptions >;
Modifiers
@public
variable SHOULD_AUTOBATCH
const SHOULD_AUTOBATCH: string;
Functions
function autoBatchEnhancer
autoBatchEnhancer: (options?: AutoBatchOptions) => StoreEnhancer;
A Redux store enhancer that watches for "low-priority" actions, and delays notifying subscribers until either the queued callback executes or the next "standard-priority" action is dispatched.
This allows dispatching multiple "low-priority" actions in a row with only a single subscriber notification to the UI after the sequence of actions is finished, thus improving UI re-render performance.
Watches for actions with the
action.meta[SHOULD_AUTOBATCH]
attribute. This can be added toaction.meta
manually, or by using theprepareAutoBatched
helper.By default, it will queue a notification for the end of the event loop tick. However, you can pass several other options to configure the behavior: -
{type: 'tick'}: queues using
queueMicrotask` (default) -{type: 'timer, timeout: number}
: queues usingsetTimeout
-{type: 'raf'}
: queues usingrequestAnimationFrame
- `{type: 'callback', queueNotification: (notify: () => void) => void}: lets you provide your own callback
function configureStore
configureStore: < S = any, A extends Action = AnyAction, M extends Middlewares<S> = [ThunkMiddleware<S, AnyAction>], E extends Enhancers = [StoreEnhancer]>( options: ConfigureStoreOptions<S, A, M, E>) => EnhancedStore<S, A, M, E>;
A friendly abstraction over the standard Redux
createStore()
function.Parameter options
The store configuration.
Returns
A configured Redux store.
Modifiers
@public
function createAction
createAction: { <P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>; <PA extends PrepareAction<any>, T extends string = string>( type: T, prepareAction: PA ): IfPrepareActionMethodProvided< PA, _ActionCreatorWithPreparedPayload<PA, T>, IsAny< ReturnType<PA>['payload'], ActionCreatorWithPayload<any, T>, IsUnknown< ReturnType<PA>['payload'], ActionCreatorWithNonInferrablePayload<T>, IfVoid< ReturnType<PA>['payload'], ActionCreatorWithoutPayload<T>, IfMaybeUndefined< ReturnType<PA>['payload'], ActionCreatorWithOptionalPayload< ReturnType<PA>['payload'], T >, ActionCreatorWithPayload<ReturnType<PA>['payload'], T> > > > > >;};
A utility function to create an action creator for the given action type string. The action creator accepts a single argument, which will be included in the action object as a field called payload. The action creator function will also have its toString() overridden so that it returns the action type, allowing it to be used in reducer logic that is looking for that action type.
Parameter type
The action type to use for created actions.
Parameter prepare
(optional) a method that takes any number of arguments and returns { payload } or { payload, meta }. If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
Modifiers
@public
function createActionCreatorInvariantMiddleware
createActionCreatorInvariantMiddleware: ( options?: ActionCreatorInvariantMiddlewareOptions) => Middleware;
function createEntityAdapter
createEntityAdapter: <T>(options?: { selectId?: IdSelector<T>; sortComparer?: false | Comparer<T>;}) => EntityAdapter<T>;
Parameter options
Modifiers
@public
function createImmutableStateInvariantMiddleware
createImmutableStateInvariantMiddleware: ( options?: ImmutableStateInvariantMiddlewareOptions) => Middleware;
Creates a middleware that checks whether any state was mutated in between dispatches or during a dispatch. If any mutations are detected, an error is thrown.
Parameter options
Middleware options.
Modifiers
@public
function createListenerMiddleware
createListenerMiddleware: < S = unknown, D extends Dispatch<AnyAction> = ThunkDispatch<S, unknown, AnyAction>, ExtraArgument = unknown>( middlewareOptions?: CreateListenerMiddlewareOptions<ExtraArgument>) => ListenerMiddlewareInstance<S, D, ExtraArgument>;
Modifiers
@public
function createReducer
createReducer: { <S extends unknown>( initialState: S | (() => S), builderCallback: (builder: ActionReducerMapBuilder<S>) => void ): ReducerWithInitialState<S>; <S extends unknown, CR extends CaseReducers<S, any> = CaseReducers<S, any>>( initialState: S | (() => S), actionsMap: CR, actionMatchers?: ActionMatcherDescriptionCollection<S>, defaultCaseReducer?: CaseReducer<S, AnyAction> ): any;};
A utility function that allows defining a reducer as a mapping from action type to *case reducer* functions that handle these action types. The reducer's initial state is passed as the first argument.
Parameter initialState
State | (() => State)
: 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 withundefined
as its state value, and is primarily useful for cases like reading initial state fromlocalStorage
.Parameter builderCallback
(builder: Builder) => void
A callback that receives a *builder* object to define case reducers via calls tobuilder.addCase(actionCreatorOrType, reducer)
.Remarks
The body of every case reducer is implicitly wrapped with a call to
produce()
from the [immer](https://github.com/mweststrate/immer) library. This means that rather than returning a new state object, you can also mutate the passed-in state object directly; these mutations will then be automatically and efficiently translated into copies, giving you both convenience and immutability.This overload accepts a callback function that receives a
builder
object as its argument. That builder providesaddCase
,addMatcher
andaddDefaultCase
functions that may be called to define what actions this reducer will handle.Example 1
import {createAction,createReducer,AnyAction,PayloadAction,} from "@reduxjs/toolkit";const increment = createAction<number>("increment");const decrement = createAction<number>("decrement");function isActionWithNumberPayload(action: AnyAction): action is PayloadAction<number> {return typeof action.payload === "number";}const reducer = createReducer({counter: 0,sumOfNumberPayloads: 0,unhandledActions: 0,},(builder) => {builder.addCase(increment, (state, action) => {// action is inferred correctly herestate.counter += action.payload;})// You can chain calls, or have separate `builder.addCase()` lines each time.addCase(decrement, (state, action) => {state.counter -= action.payload;})// You can apply a "matcher function" to incoming actions.addMatcher(isActionWithNumberPayload, (state, action) => {})// and provide a default case if no other handlers matched.addDefaultCase((state, action) => {});});Modifiers
@public
A utility function that allows defining a reducer as a mapping from action type to *case reducer* functions that handle these action types. The reducer's initial state is passed as the first argument.
The body of every case reducer is implicitly wrapped with a call to
produce()
from the [immer](https://github.com/mweststrate/immer) library. This means that rather than returning a new state object, you can also mutate the passed-in state object directly; these mutations will then be automatically and efficiently translated into copies, giving you both convenience and immutability.This overload accepts an object where the keys are string action types, and the values are case reducer functions to handle those action types.
Parameter initialState
State | (() => State)
: 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 withundefined
as its state value, and is primarily useful for cases like reading initial state fromlocalStorage
.Parameter actionsMap
An object mapping from action types to _case reducers_, each of which handles one specific action type.
Parameter actionMatchers
An array of matcher definitions in the form
{matcher, reducer}
. All matching reducers will be executed in order, independently if a case reducer matched or not.Parameter defaultCaseReducer
A "default case" reducer that is executed if no case reducer and no matcher reducer was executed for this action.
Example 1
const counterReducer = createReducer(0, {increment: (state, action) => state + action.payload,decrement: (state, action) => state - action.payload})// Alternately, use a "lazy initializer" to provide the initial state// (works with either form of createReducer)const initialState = () => 0const counterReducer = createReducer(initialState, {increment: (state, action) => state + action.payload,decrement: (state, action) => state - action.payload})Action creators that were generated using [
createAction
](./createAction) may be used directly as the keys here, using computed property syntax:const increment = createAction('increment')const decrement = createAction('decrement')const counterReducer = createReducer(0, {[increment]: (state, action) => state + action.payload,[decrement.type]: (state, action) => state - action.payload})Modifiers
@public
function createSerializableStateInvariantMiddleware
createSerializableStateInvariantMiddleware: ( options?: SerializableStateInvariantMiddlewareOptions) => Middleware;
Creates a middleware that, after every state change, checks if the new state is serializable. If a non-serializable value is found within the state, an error is printed to the console.
Parameter options
Middleware options.
Modifiers
@public
function createSlice
createSlice: < State, CaseReducers extends SliceCaseReducers<State>, Name extends string = string>( options: CreateSliceOptions<State, CaseReducers, Name>) => Slice<State, CaseReducers, Name>;
A function that accepts an initial state, an object full of reducer functions, and a "slice name", and automatically generates action creators and action types that correspond to the reducers and state.
The
reducer
argument is passed tocreateReducer()
.Modifiers
@public
function findNonSerializableValue
findNonSerializableValue: ( value: unknown, path?: string, isSerializable?: (value: unknown) => boolean, getEntries?: (value: unknown) => [string, any][], ignoredPaths?: IgnorePaths, cache?: WeakSet<object>) => NonSerializableValue | false;
Modifiers
@public
function getDefaultMiddleware
getDefaultMiddleware: < S = any, O extends Partial<GetDefaultMiddlewareOptions> = { thunk: true; immutableCheck: true; serializableCheck: true; actionCreatorCheck: true; }>( options?: O) => MiddlewareArray<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;
Returns any array containing the default middleware installed by
configureStore()
. Useful if you want to configure your store with a custommiddleware
array but still keep the default set.The default middleware used by
configureStore()
.Modifiers
@public
Deprecated
Prefer to use the callback notation for the
middleware
option inconfigureStore
to access a pre-typedgetDefaultMiddleware
instead.
function getType
getType: <T extends string>(actionCreator: PayloadActionCreator<any, T>) => T;
Returns the action type of the actions created by the passed
createAction()
-generated action creator (arbitrary action creators are not supported).Parameter action
The action creator whose action type to get.
Returns
The action type used by the action creator.
Modifiers
@public
function isAction
isAction: (action: unknown) => action is Action<unknown>;
Returns true if value is a plain object with a
type
property.
function isActionCreator
isActionCreator: ( action: unknown) => action is BaseActionCreator<unknown, string, never, never> & Function;
Returns true if value is an RTK-like action creator, with a static type property and match method.
function isAllOf
isAllOf: <Matchers extends Matcher<any>[]>( ...matchers: Matchers) => ( action: any) => action is UnionToIntersection<ActionFromMatcher<Matchers[number]>>;
A higher-order function that returns a function that may be used to check whether an action matches all of the supplied type guards or action creators.
Parameter matchers
The type guards or action creators to match against.
Modifiers
@public
function isAnyOf
isAnyOf: <Matchers extends Matcher<any>[]>( ...matchers: Matchers) => (action: any) => action is ActionFromMatcher<Matchers[number]>;
A higher-order function that returns a function that may be used to check whether an action matches any one of the supplied type guards or action creators.
Parameter matchers
The type guards or action creators to match against.
Modifiers
@public
function isAsyncThunkAction
isAsyncThunkAction: { (): (action: any) => action is UnknownAsyncThunkAction; <AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>( ...asyncThunks: AsyncThunks ): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>; (action: any): action is UnknownAsyncThunkAction;};
A higher-order function that returns a function that may be used to check whether an action was created by an async thunk action creator.
Modifiers
@public
A higher-order function that returns a function that may be used to check whether an action belongs to one of the provided async thunk action creators.
Parameter asyncThunks
(optional) The async thunk action creators to match against.
Modifiers
@public
Tests if
action
is a thunk actionModifiers
@public
function isFluxStandardAction
isFluxStandardAction: ( action: unknown) => action is { type: string; payload?: unknown; error?: unknown; meta?: unknown };
Returns true if value is an action with a string type and valid Flux Standard Action keys.
function isFulfilled
isFulfilled: { (): ( action: any ) => action is PayloadAction< unknown, string, { arg: unknown; requestId: string; requestStatus: 'fulfilled' }, never >; <AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>( ...asyncThunks: AsyncThunks ): ( action: any ) => action is ActionFromMatcher<AsyncThunks[number]['fulfilled']>; (action: any): action is PayloadAction< unknown, string, { arg: unknown; requestId: string; requestStatus: 'fulfilled' }, never >;};
A higher-order function that returns a function that may be used to check whether an action was created by an async thunk action creator, and that the action is fulfilled.
Modifiers
@public
A higher-order function that returns a function that may be used to check whether an action belongs to one of the provided async thunk action creators, and that the action is fulfilled.
Parameter asyncThunks
(optional) The async thunk action creators to match against.
Modifiers
@public
Tests if
action
is a fulfilled thunk actionModifiers
@public
function isImmutableDefault
isImmutableDefault: (value: unknown) => boolean;
The default
isImmutable
function.Modifiers
@public
function isPending
isPending: { (): ( action: any ) => action is PayloadAction< undefined, string, { arg: unknown; requestId: string; requestStatus: 'pending' }, never >; <AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>( ...asyncThunks: AsyncThunks ): (action: any) => action is ActionFromMatcher<AsyncThunks[number]['pending']>; (action: any): action is PayloadAction< undefined, string, { arg: unknown; requestId: string; requestStatus: 'pending' }, never >;};
A higher-order function that returns a function that may be used to check whether an action was created by an async thunk action creator, and that the action is pending.
Modifiers
@public
A higher-order function that returns a function that may be used to check whether an action belongs to one of the provided async thunk action creators, and that the action is pending.
Parameter asyncThunks
(optional) The async thunk action creators to match against.
Modifiers
@public
Tests if
action
is a pending thunk actionModifiers
@public
function isPlain
isPlain: (val: any) => boolean;
Returns true if the passed value is "plain", i.e. a value that is either directly JSON-serializable (boolean, number, string, array, plain object) or
undefined
.Parameter val
The value to check.
Modifiers
@public
function isPlainObject
isPlainObject: (value: unknown) => value is object;
Returns true if the passed value is "plain" object, i.e. an object whose prototype is the root
Object.prototype
. This includes objects created using object literals, but not for instance for class instances.Parameter value
The value to inspect.
Returns
{boolean} True if the argument appears to be a plain object.
Modifiers
@public
function isRejected
isRejected: { (): ( action: any ) => action is PayloadAction< unknown, string, { arg: unknown; requestId: string; requestStatus: 'rejected'; aborted: boolean; condition: boolean; } & ({ rejectedWithValue: true } | ({ rejectedWithValue: false } & {})), SerializedError >; <AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>( ...asyncThunks: AsyncThunks ): (action: any) => action is ActionFromMatcher<AsyncThunks[number]['rejected']>; (action: any): action is PayloadAction< unknown, string, { arg: unknown; requestId: string; requestStatus: 'rejected'; aborted: boolean; condition: boolean; } & ({ rejectedWithValue: true } | ({ rejectedWithValue: false } & {})), SerializedError >;};
A higher-order function that returns a function that may be used to check whether an action was created by an async thunk action creator, and that the action is rejected.
Modifiers
@public
A higher-order function that returns a function that may be used to check whether an action belongs to one of the provided async thunk action creators, and that the action is rejected.
Parameter asyncThunks
(optional) The async thunk action creators to match against.
Modifiers
@public
Tests if
action
is a rejected thunk actionModifiers
@public
function isRejectedWithValue
isRejectedWithValue: { (): ( action: any ) => action is PayloadAction< unknown, string, { arg: unknown; requestId: string; requestStatus: 'rejected'; aborted: boolean; condition: boolean; } & ({ rejectedWithValue: true } | ({ rejectedWithValue: false } & {})), SerializedError >; <AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>( ...asyncThunks: AsyncThunks ): ( action: any ) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>; (action: any): action is PayloadAction< unknown, string, { arg: unknown; requestId: string; requestStatus: 'rejected'; aborted: boolean; condition: boolean; } & ({ rejectedWithValue: true } | ({ rejectedWithValue: false } & {})), SerializedError >;};
A higher-order function that returns a function that may be used to check whether an action was created by an async thunk action creator, and that the action is rejected with value.
Modifiers
@public
A higher-order function that returns a function that may be used to check whether an action belongs to one of the provided async thunk action creators, and that the action is rejected with value.
Parameter asyncThunks
(optional) The async thunk action creators to match against.
Modifiers
@public
Tests if
action
is a rejected thunk action with valueModifiers
@public
function miniSerializeError
miniSerializeError: (value: any) => SerializedError;
Serializes an error into a plain object. Reworked from https://github.com/sindresorhus/serialize-error
Modifiers
@public
function nanoid
nanoid: (size?: number) => string;
Modifiers
@public
function prepareAutoBatched
prepareAutoBatched: <T>() => (payload: T) => { payload: T; meta: unknown };
function unwrapResult
unwrapResult: <R extends UnwrappableAction>( action: R) => UnwrappedActionPayload<R>;
Modifiers
@public
Classes
class EnhancerArray
class EnhancerArray<Enhancers extends StoreEnhancer<any, any>[]> extends Array< Enhancers[number]> {}
Modifiers
@public
constructor
constructor(...items: StoreEnhancer<any, any>[]);
property [Symbol.species]
static readonly [Symbol.species]: any;
method concat
concat: { <AdditionalEnhancers extends readonly StoreEnhancer<any, any>[]>( items: AdditionalEnhancers ): EnhancerArray<[...Enhancers, ...AdditionalEnhancers]>; <AdditionalEnhancers extends readonly StoreEnhancer<any, any>[]>( ...items: AdditionalEnhancers ): EnhancerArray<[...Enhancers, ...AdditionalEnhancers]>;};
method prepend
prepend: { <AdditionalEnhancers extends readonly StoreEnhancer<any, any>[]>( items: AdditionalEnhancers ): EnhancerArray<[...AdditionalEnhancers, ...Enhancers]>; <AdditionalEnhancers extends readonly StoreEnhancer<any, any>[]>( ...items: AdditionalEnhancers ): EnhancerArray<[...AdditionalEnhancers, ...Enhancers]>;};
class MiddlewareArray
class MiddlewareArray<Middlewares extends Middleware<any, any>[]> extends Array< Middlewares[number]> {}
Modifiers
@public
constructor
constructor(...items: Middleware<any, any>[]);
property [Symbol.species]
static readonly [Symbol.species]: any;
method concat
concat: { <AdditionalMiddlewares extends readonly Middleware<any, any>[]>( items: AdditionalMiddlewares ): MiddlewareArray<[...Middlewares, ...AdditionalMiddlewares]>; <AdditionalMiddlewares extends readonly Middleware<any, any>[]>( ...items: AdditionalMiddlewares ): MiddlewareArray<[...Middlewares, ...AdditionalMiddlewares]>;};
method prepend
prepend: { <AdditionalMiddlewares extends readonly Middleware<any, any>[]>( items: AdditionalMiddlewares ): MiddlewareArray<[...AdditionalMiddlewares, ...Middlewares]>; <AdditionalMiddlewares extends readonly Middleware<any, any>[]>( ...items: AdditionalMiddlewares ): MiddlewareArray<[...AdditionalMiddlewares, ...Middlewares]>;};
class TaskAbortError
class TaskAbortError implements SerializedError {}
constructor
constructor(code: string);
property code
code: string;
property message
message: string;
property name
name: string;
Interfaces
interface ActionCreatorInvariantMiddlewareOptions
interface ActionCreatorInvariantMiddlewareOptions {}
property isActionCreator
isActionCreator?: (action: unknown) => action is Function & { type?: unknown;};
The function to identify whether a value is an action creator. The default checks for a function with a static type property and match method.
interface ActionCreatorWithNonInferrablePayload
interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {}
An action creator of type
T
whosepayload
type could not be inferred. Accepts everything aspayload
.{redux#ActionCreator}
Modifiers
@public
call signature
<PT extends unknown>(payload: PT): PayloadAction<PT, T>;
Calling this redux#ActionCreator with an argument will return a PayloadAction of type
T
with a payload of exactly the type of the argument.
interface ActionCreatorWithOptionalPayload
interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {}
An action creator of type
T
that takes an optional payload of typeP
.{redux#ActionCreator}
Modifiers
@public
call signature
(payload?: P): PayloadAction<P, T>;
Calling this redux#ActionCreator with an argument will return a PayloadAction of type
T
with a payload ofP
. Calling it without an argument will return a PayloadAction with a payload ofundefined
.
interface ActionCreatorWithoutPayload
interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {}
An action creator of type
T
that takes no payload.{redux#ActionCreator}
Modifiers
@public
call signature
(noArgument: void): PayloadAction<undefined, T>;
Calling this redux#ActionCreator will return a PayloadAction of type
T
with a payload ofundefined
interface ActionCreatorWithPayload
interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {}
An action creator of type
T
that requires a payload of type P.{redux#ActionCreator}
Modifiers
@public
call signature
(payload: P): PayloadAction<P, T>;
Calling this redux#ActionCreator with an argument will return a PayloadAction of type
T
with a payload ofP
interface ActionCreatorWithPreparedPayload
interface ActionCreatorWithPreparedPayload< Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {}
An action creator that takes multiple arguments that are passed to a
PrepareAction
method to create the final Action.Modifiers
@public
call signature
(...args: Args): PayloadAction<P, T, M, E>;
Calling this redux#ActionCreator with
Args
will return an Action with a payload of typeP
and (depending on thePrepareAction
method used) ameta
- anderror
property of typesM
andE
respectively.
interface ActionReducerMapBuilder
interface ActionReducerMapBuilder<State> {}
A builder for an action <-> reducer map.
Modifiers
@public
method addCase
addCase: { <ActionCreator extends TypedActionCreator<string>>( actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>> ): ActionReducerMapBuilder<State>; <Type extends string, A extends Action<Type>>( type: Type, reducer: CaseReducer<State, A> ): ActionReducerMapBuilder<State>;};
Adds a case reducer to handle a single exact action type.
Parameter actionCreator
Either a plain action type string, or an action creator generated by [
createAction
](./createAction) that can be used to determine the action type.Parameter reducer
The actual case reducer function.
Remarks
All calls to
builder.addCase
must come before any calls tobuilder.addMatcher
orbuilder.addDefaultCase
.
method addDefaultCase
addDefaultCase: (reducer: CaseReducer<State, AnyAction>) => {};
Adds a "default case" reducer that is executed if no case reducer and no matcher reducer was executed for this action.
Parameter reducer
The fallback "default case" reducer function.
Example 1
```ts import { createReducer } from '@reduxjs/toolkit' const initialState = { otherActions: 0 } const reducer = createReducer(initialState, builder => { builder // .addCase(...) // .addMatcher(...) .addDefaultCase((state, action) => { state.otherActions++ }) }) ```
method addMatcher
addMatcher: <A>( matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends AnyAction ? A : A & AnyAction>) => Omit<ActionReducerMapBuilder<State>, 'addCase'>;
Allows you to match your incoming actions against your own filter function instead of only the
action.type
property.Parameter matcher
A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) function
Parameter reducer
The actual case reducer function.
Remarks
If multiple matcher reducers match, all of them will be executed in the order they were defined in - even if a case reducer already matched. All calls to
builder.addMatcher
must come after any calls tobuilder.addCase
and before any calls tobuilder.addDefaultCase
.Example 1
```ts import { createAction, createReducer, AsyncThunk, AnyAction, } from "@reduxjs/toolkit";
type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;
type PendingAction = ReturnType<GenericAsyncThunk["pending"]>; type RejectedAction = ReturnType<GenericAsyncThunk["rejected"]>; type FulfilledAction = ReturnType<GenericAsyncThunk["fulfilled"]>;
const initialState: Record<string, string> = {}; const resetAction = createAction("reset-tracked-loading-state");
function isPendingAction(action: AnyAction): action is PendingAction { return action.type.endsWith("/pending"); }
const reducer = createReducer(initialState, (builder) => { builder .addCase(resetAction, () => initialState) // matcher can be defined outside as a type predicate function .addMatcher(isPendingAction, (state, action) => { state[action.meta.requestId] = "pending"; }) .addMatcher( // matcher can be defined inline as a type predicate function (action): action is RejectedAction => action.type.endsWith("/rejected"), (state, action) => { state[action.meta.requestId] = "rejected"; } ) // matcher can just return boolean and the matcher can receive a generic argument .addMatcher( (action) => action.type.endsWith("/fulfilled"), (state, action) => { state[action.meta.requestId] = "fulfilled"; } ); }); ```
interface AsyncTaskExecutor
interface AsyncTaskExecutor<T> {}
Modifiers
@public
call signature
(forkApi: ForkedTaskAPI): Promise<T>;
interface ConfigureStoreOptions
interface ConfigureStoreOptions< S = any, A extends Action = AnyAction, M extends Middlewares<S> = Middlewares<S>, E extends Enhancers = Enhancers> {}
Options for
configureStore()
.Modifiers
@public
property devTools
devTools?: boolean | DevToolsOptions;
Whether to enable Redux DevTools integration. Defaults to
true
.Additional configuration can be done by passing Redux DevTools options
property enhancers
enhancers?: E | ConfigureEnhancersCallback<E>;
The store enhancers to apply. See Redux's
createStore()
. All enhancers will be included before the DevTools Extension enhancer. If you need to customize the order of enhancers, supply a callback function that will receive the original array (ie,[applyMiddleware]
), and should return a new array (such as[applyMiddleware, offline]
). If you only need to add middleware, you can use themiddleware
parameter instead.
property middleware
middleware?: ((getDefaultMiddleware: CurriedGetDefaultMiddleware<S>) => M) | M;
An array of Redux middleware to install. If not supplied, defaults to the set of middleware returned by
getDefaultMiddleware()
.Example 1
middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)
See Also
https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
property preloadedState
preloadedState?: PreloadedState<CombinedState<NoInfer<S>>>;
The initial state, same as Redux's createStore. You may optionally specify it to hydrate the state from the server in universal apps, or to restore a previously serialized user session. If you use
combineReducers()
to produce the root reducer function (either directly or indirectly by passing an object asreducer
), this must be an object with the same shape as the reducer map keys.
property reducer
reducer: Reducer<S, A> | ReducersMapObject<S, A>;
A single reducer function that will be used as the root reducer, or an object of slice reducers that will be passed to
combineReducers()
.
interface CreateListenerMiddlewareOptions
interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {}
Modifiers
@public
interface CreateSliceOptions
interface CreateSliceOptions< State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string> {}
Options for
createSlice()
.Modifiers
@public
property extraReducers
extraReducers?: | CaseReducers<NoInfer<State>, any> | ((builder: ActionReducerMapBuilder<NoInfer<State>>) => void);
A callback that receives a *builder* object to define case reducers via calls to
builder.addCase(actionCreatorOrType, reducer)
.Alternatively, a mapping from action types to action-type-specific *case reducer* functions. These reducers should have existing action types used as the keys, and action creators will _not_ be generated.
Example 1
```ts import { createAction, createSlice, Action, AnyAction } from '@reduxjs/toolkit' const incrementBy = createAction('incrementBy') const decrement = createAction('decrement')
interface RejectedAction extends Action { error: Error }
function isRejectedAction(action: AnyAction): 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) => {}) } }) ```
property initialState
initialState: State | (() => State);
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 fromlocalStorage
.
property name
name: Name;
The slice's name. Used to namespace the generated action types.
property reducers
reducers: ValidateSliceCaseReducers<State, CR>;
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()
.
interface DevToolsEnhancerOptions
interface DevToolsEnhancerOptions {}
Modifiers
@public
property actionCreators
actionCreators?: | ActionCreator<any>[] | { [key: string]: ActionCreator<any>; };
action creators functions to be available in the Dispatcher.
property actionsAllowlist
actionsAllowlist?: string | string[];
*string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers). If
actionsAllowlist
specified,actionsDenylist
is ignored.
property actionSanitizer
actionSanitizer?: <A extends Action>(action: A, id: number) => A;
function which takes
action
object and id number as arguments, and should returnaction
object back.
property actionsBlacklist
actionsBlacklist?: string | string[];
*string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers). If
actionsWhitelist
specified,actionsBlacklist
is ignored.Deprecated
Use actionsDenylist instead.
property actionsDenylist
actionsDenylist?: string | string[];
*string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers). If
actionsAllowlist
specified,actionsDenylist
is ignored.
property actionsWhitelist
actionsWhitelist?: string | string[];
*string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers). If
actionsWhitelist
specified,actionsBlacklist
is ignored.Deprecated
Use actionsAllowlist instead.
property autoPause
autoPause?: boolean;
auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use. Not available for Redux enhancer (as it already does it but storing the data to be sent).
false
property features
features?: { /** * start/pause recording of dispatched actions */ pause?: boolean; /** * lock/unlock dispatching actions and side effects */ lock?: boolean; /** * persist states on page reloading */ persist?: boolean; /** * export history of actions in a file */ export?: boolean | 'custom'; /** * import history of actions from a file */ import?: boolean | 'custom'; /** * jump back and forth (time travelling) */ jump?: boolean; /** * skip (cancel) actions */ skip?: boolean; /** * drag and drop actions in the history list */ reorder?: boolean; /** * dispatch custom actions or action creators */ dispatch?: boolean; /** * generate tests for the selected actions */ test?: boolean;};
If you want to restrict the extension, specify the features you allow. If not specified, all of the features are enabled. When set as an object, only those included as
true
will be allowed. Note that excepttrue
/false
,import
andexport
can be set ascustom
(which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side. Otherwise, you'll get/set the data right from the monitor part.
property latency
latency?: number;
if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once. It is the joint between performance and speed. When set to
0
, all actions will be sent instantly. Set it to a higher value when experiencing perf issues (alsomaxAge
to a lower value).500 ms.
property maxAge
maxAge?: number;
(> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
50
property name
name?: string;
the instance name to be showed on the monitor page. Default value is
document.title
. If not specified and there's no document title, it will consist oftabId
andinstanceId
.
property pauseActionType
pauseActionType?: string;
if specified, whenever clicking on
Pause recording
button and there are actions in the history log, will add this action type. If not specified, will commit when paused. Available only for Redux enhancer."@@PAUSED""
property predicate
predicate?: <S, A extends Action>(state: S, action: A) => boolean;
called for every action before sending, takes
state
andaction
object, and returnstrue
in case it allows sending the current data to the monitor. Use it as a more advanced version ofactionsDenylist
/actionsAllowlist
parameters.
property serialize
serialize?: | boolean | { /** * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode). * - `false` - will handle also circular references. * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions. * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys. * For each of them you can indicate if to include (by setting as `true`). * For `function` key you can also specify a custom function which handles serialization. * See [`jsan`](https://github.com/kolodny/jsan) for more details. */ options?: | undefined | boolean | { date?: true; regex?: true; undefined?: true; error?: true; symbol?: true; map?: true; set?: true; function?: true | ((fn: (...args: any[]) => any) => string); }; /** * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify. * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4) * key. So you can deserialize it back while importing or persisting data. * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png): */ replacer?: (key: string, value: unknown) => any; /** * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter) * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41) * as an example on how to serialize special data types and get them back. */ reviver?: (key: string, value: unknown) => any; /** * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize). * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back. * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`. */ immutable?: any; /** * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting... */ refs?: any; };
Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you were to pass an object and specify
options
as a boolean. Giving an object allows fine-grained customization using thereplacer
andreviver
functions.
property shouldCatchErrors
shouldCatchErrors?: boolean;
if specified as
true
, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.false
property shouldHotReload
shouldHotReload?: boolean;
if set to
false
, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.true
property shouldRecordChanges
shouldRecordChanges?: boolean;
if specified as
false
, it will not record the changes till clicking onStart recording
button. Available only for Redux enhancer, for others useautoPause
.true
property shouldStartLocked
shouldStartLocked?: boolean;
if specified as
true
, it will not allow any non-monitor actions to be dispatched till clicking onUnlock changes
button. Available only for Redux enhancer.false
property stateSanitizer
stateSanitizer?: <S>(state: S, index: number) => S;
function which takes
state
object and index as arguments, and should returnstate
object back.
property trace
trace?: boolean | (<A extends Action>(action: A) => string);
Set to true or a stacktrace-returning function to record call stack traces for dispatched actions. Defaults to false.
property traceLimit
traceLimit?: number;
The maximum number of stack trace entries to record per action. Defaults to 10.
interface Dictionary
interface Dictionary<T> extends DictionaryNum<T> {}
Modifiers
@public
index signature
[id: string]: T | undefined;
interface EntityAdapter
interface EntityAdapter<T> extends EntityStateAdapter<T> {}
Modifiers
@public
property selectId
selectId: IdSelector<T>;
property sortComparer
sortComparer: false | Comparer<T>;
method getInitialState
getInitialState: { (): EntityState<T>; <S extends object>(state: S): EntityState<T> & S;};
method getSelectors
getSelectors: { (): EntitySelectors<T, EntityState<T>>; <V>(selectState: (state: V) => EntityState<T>): EntitySelectors<T, V>;};
interface EntitySelectors
interface EntitySelectors<T, V> {}
Modifiers
@public
property selectAll
selectAll: (state: V) => T[];
property selectById
selectById: (state: V, id: EntityId) => T | undefined;
property selectEntities
selectEntities: (state: V) => Dictionary<T>;
property selectIds
selectIds: (state: V) => EntityId[];
property selectTotal
selectTotal: (state: V) => number;
interface EntityState
interface EntityState<T> {}
Modifiers
@public
interface EntityStateAdapter
interface EntityStateAdapter<T> {}
Modifiers
@public
method addMany
addMany: { <S extends EntityState<T>>( state: PreventAny<S, T>, entities: readonly T[] | Record<EntityId, T> ): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, entities: { payload: readonly T[] | Record<EntityId, T>; type: string } ): S;};
method addOne
addOne: { <S extends EntityState<T>>(state: PreventAny<S, T>, entity: T): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, action: { payload: T; type: string } ): S;};
method removeAll
removeAll: <S extends EntityState<T>>(state: PreventAny<S, T>) => S;
method removeMany
removeMany: { <S extends EntityState<T>>( state: PreventAny<S, T>, keys: readonly EntityId[] ): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, keys: { payload: readonly EntityId[]; type: string } ): S;};
method removeOne
removeOne: { <S extends EntityState<T>>(state: PreventAny<S, T>, key: EntityId): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, key: { payload: EntityId; type: string } ): S;};
method setAll
setAll: { <S extends EntityState<T>>( state: PreventAny<S, T>, entities: readonly T[] | Record<EntityId, T> ): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, entities: { payload: readonly T[] | Record<EntityId, T>; type: string } ): S;};
method setMany
setMany: { <S extends EntityState<T>>( state: PreventAny<S, T>, entities: readonly T[] | Record<EntityId, T> ): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, entities: { payload: readonly T[] | Record<EntityId, T>; type: string } ): S;};
method setOne
setOne: { <S extends EntityState<T>>(state: PreventAny<S, T>, entity: T): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, action: { payload: T; type: string } ): S;};
method updateMany
updateMany: { <S extends EntityState<T>>( state: PreventAny<S, T>, updates: ReadonlyArray<Update<T>> ): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, updates: { payload: readonly Update<T>[]; type: string } ): S;};
method updateOne
updateOne: { <S extends EntityState<T>>(state: PreventAny<S, T>, update: Update<T>): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, update: { payload: Update<T>; type: string } ): S;};
method upsertMany
upsertMany: { <S extends EntityState<T>>( state: PreventAny<S, T>, entities: readonly T[] | Record<EntityId, T> ): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, entities: { payload: readonly T[] | Record<EntityId, T>; type: string } ): S;};
method upsertOne
upsertOne: { <S extends EntityState<T>>(state: PreventAny<S, T>, entity: T): S; <S extends EntityState<T>>( state: IsAny<S, EntityState<T>, S>, entity: { payload: T; type: string } ): S;};
interface ForkedTask
interface ForkedTask<T> {}
Modifiers
@public
property result
result: Promise<TaskResult<T>>;
A promise that resolves when the task is either completed or cancelled or rejects if parent listener execution is cancelled or completed.
### Example
const result = await fork(async (forkApi) => Promise.resolve(4)).resultif(result.status === 'ok') {console.log(result.value) // logs 4}}
method cancel
cancel: () => void;
Cancel task if it is in progress or not yet started, it is noop otherwise.
interface ForkedTaskAPI
interface ForkedTaskAPI {}
Modifiers
@public
property signal
signal: AbortSignal;
An abort signal whose
aborted
property is set totrue
if the task execution is either aborted or completed.See Also
https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
method delay
delay: (timeoutMs: number) => Promise<void>;
Returns a promise that resolves after
timeoutMs
or rejects if the task or the parent listener has been cancelled or is completed.Parameter timeoutMs
method pause
pause: <W>(waitFor: Promise<W>) => Promise<W>;
Returns a promise that resolves when
waitFor
resolves or rejects if the task or the parent listener has been cancelled or is completed.
interface ImmutableStateInvariantMiddlewareOptions
interface ImmutableStateInvariantMiddlewareOptions {}
Options for
createImmutableStateInvariantMiddleware()
.Modifiers
@public
property ignore
ignore?: string[];
property ignoredPaths
ignoredPaths?: IgnorePaths;
An array of dot-separated path strings that match named nodes from the root state to ignore when checking for immutability. Defaults to undefined
property isImmutable
isImmutable?: IsImmutableFunc;
Callback function to check if a value is considered to be immutable. This function is applied recursively to every value contained in the state. The default implementation will return true for primitive types (like numbers, strings, booleans, null and undefined).
property warnAfter
warnAfter?: number;
Print a warning if checks take longer than N ms. Default: 32ms
interface ListenerEffectAPI
interface ListenerEffectAPI< State, Dispatch extends ReduxDispatch<AnyAction>, ExtraArgument = unknown> extends MiddlewareAPI<Dispatch, State> {}
Modifiers
@public
property cancelActiveListeners
cancelActiveListeners: () => void;
Cancels all other running instances of this same listener except for the one that made this call.
property condition
condition: ConditionFunction<State>;
Returns a promise that resolves when the input predicate returns
true
or rejects if the listener has been cancelled or is completed.The return value is
true
if the predicate succeeds orfalse
if a timeout is provided and expires first.### Example
const updateBy = createAction<number>('counter/updateBy');middleware.startListening({actionCreator: updateBy,async effect(_, { condition }) {// wait at most 3s for `updateBy` actions.if(await condition(updateBy.match, 3_000)) {// `updateBy` has been dispatched twice in less than 3s.}}})
property extra
extra: ExtraArgument;
property getOriginalState
getOriginalState: () => State;
Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.
### Synchronous invocation
This function can **only** be invoked **synchronously**, it throws error otherwise.
Example 1
middleware.startListening({predicate: () => true,async effect(_, { getOriginalState }) {getOriginalState(); // sync: OK!setTimeout(getOriginalState, 0); // async: throws Errorawait Promise().resolve();getOriginalState() // async: throws Error}})
property signal
signal: AbortSignal;
An abort signal whose
aborted
property is set totrue
if the listener execution is either aborted or completed.See Also
https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
property take
take: TakePattern<State>;
Returns a promise that resolves when the input predicate returns
true
or rejects if the listener has been cancelled or is completed.The return value is the
[action, currentState, previousState]
combination that the predicate saw as arguments.The promise resolves to null if a timeout is provided and expires first,
### Example
const updateBy = createAction<number>('counter/updateBy');middleware.startListening({actionCreator: updateBy,async effect(_, { take }) {const [{ payload }] = await take(updateBy.match);console.log(payload); // logs 5;}})store.dispatch(updateBy(5));
method delay
delay: (timeoutMs: number) => Promise<void>;
Returns a promise that resolves after
timeoutMs
or rejects if the listener has been cancelled or is completed.
method fork
fork: <T>( executor: ForkedTaskExecutor<T>, options?: ForkOptions) => ForkedTask<T>;
Queues in the next microtask the execution of a task.
Parameter executor
Parameter options
method pause
pause: <M>(promise: Promise<M>) => Promise<M>;
Returns a promise that resolves when
waitFor
resolves or rejects if the listener has been cancelled or is completed.Parameter promise
method subscribe
subscribe: () => void;
It will subscribe a listener if it was previously removed, noop otherwise.
method unsubscribe
unsubscribe: () => void;
Removes the listener entry from the middleware and prevent future instances of the listener from running.
It does **not** cancel any active instances.
interface ListenerErrorHandler
interface ListenerErrorHandler {}
Gets notified with synchronous and asynchronous errors raised by
listeners
orpredicates
.Parameter error
The thrown error.
Parameter errorInfo
Additional information regarding the thrown error.
Modifiers
@public
call signature
(error: unknown, errorInfo: ListenerErrorInfo): void;
interface ListenerMiddlewareInstance
interface ListenerMiddlewareInstance< State = unknown, Dispatch extends ThunkDispatch<State, unknown, AnyAction> = ThunkDispatch< State, unknown, AnyAction >, ExtraArgument = unknown> {}
Modifiers
@public
property clearListeners
clearListeners: () => void;
Unsubscribes all listeners, cancels running listeners and tasks.
property middleware
middleware: ListenerMiddleware<State, Dispatch, ExtraArgument>;
property startListening
startListening: AddListenerOverloads< UnsubscribeListener, State, Dispatch, ExtraArgument>;
property stopListening
stopListening: RemoveListenerOverloads<State, Dispatch>;
interface SerializableStateInvariantMiddlewareOptions
interface SerializableStateInvariantMiddlewareOptions {}
Options for
createSerializableStateInvariantMiddleware()
.Modifiers
@public
property disableCache
disableCache?: boolean;
Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes. The cache is automatically disabled if no browser support for WeakSet is present.
property getEntries
getEntries?: (value: any) => [string, any][];
The function that will be used to retrieve entries from each value. If unspecified,
Object.entries
will be used. Defaults toundefined
.
property ignoreActions
ignoreActions?: boolean;
Opt out of checking actions. When set to
true
, other action-related params will be ignored.
property ignoredActionPaths
ignoredActionPaths?: (string | RegExp)[];
An array of dot-separated path strings or regular expressions to ignore when checking for serializability, Defaults to ['meta.arg', 'meta.baseQueryMeta']
property ignoredActions
ignoredActions?: string[];
An array of action types to ignore when checking for serializability. Defaults to []
property ignoredPaths
ignoredPaths?: (string | RegExp)[];
An array of dot-separated path strings or regular expressions to ignore when checking for serializability, Defaults to []
property ignoreState
ignoreState?: boolean;
Opt out of checking state. When set to
true
, other state-related params will be ignored.
property isSerializable
isSerializable?: (value: any) => boolean;
The function to check if a value is considered serializable. This function is applied recursively to every value contained in the state. Defaults to
isPlain()
.
property warnAfter
warnAfter?: number;
Execution time warning threshold. If the middleware takes longer than
warnAfter
ms, a warning will be displayed in the console. Defaults to 32ms.
interface SerializedError
interface SerializedError {}
Modifiers
@public
interface Slice
interface Slice< State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string> {}
The return value of
createSlice
Modifiers
@public
property actions
actions: CaseReducerActions<CaseReducers, Name>;
Action creators for the types of actions that are handled by the slice reducer.
property caseReducers
caseReducers: SliceDefinedCaseReducers<CaseReducers>;
The individual case reducer functions that were passed in the
reducers
parameter. This enables reuse and testing if they were defined inline when callingcreateSlice
.
property getInitialState
getInitialState: () => State;
Provides access to the initial state value given to the slice. If a lazy state initializer was provided, it will be called and a fresh value returned.
property name
name: Name;
The slice name.
property reducer
reducer: Reducer<State>;
The slice's reducer.
interface SyncTaskExecutor
interface SyncTaskExecutor<T> {}
Modifiers
@public
call signature
(forkApi: ForkedTaskAPI): T;
interface UnsubscribeListenerOptions
interface UnsubscribeListenerOptions {}
Modifiers
@public
property cancelActive
cancelActive?: true;
Type Aliases
type ActionMatchingAllOf
type ActionMatchingAllOf<Matchers extends [...Matcher<any>[]]> = UnionToIntersection< ActionMatchingAnyOf<Matchers>>;
Modifiers
@public
type ActionMatchingAnyOf
type ActionMatchingAnyOf<Matchers extends [...Matcher<any>[]]> = ActionFromMatcher< Matchers[number]>;
Modifiers
@public
type Actions
type Actions<T extends keyof any = string> = Record<T, Action>;
Defines a mapping from action types to corresponding action object shapes.
Modifiers
@public
Deprecated
This should not be used manually - it is only used for internal inference purposes and should not have any further value. It might be removed in the future.
type AsyncThunk
type AsyncThunk< Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & { pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>; rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>; fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>; typePrefix: string;};
A type describing the return value of
createAsyncThunk
. Might be useful for wrappingcreateAsyncThunk
in custom abstractions.Modifiers
@public
type AsyncThunkAction
type AsyncThunkAction< Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = ( dispatch: GetDispatch<ThunkApiConfig>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => Promise< | ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & { abort: (reason?: string) => void; requestId: string; arg: ThunkArg; unwrap: () => Promise<Returned>;};
A ThunkAction created by
createAsyncThunk
. Dispatching it returns a Promise for either a fulfilled or rejected action. Also, the returned value contains anabort()
method that allows the asyncAction to be cancelled from the outside.Modifiers
@public
type AsyncThunkOptions
type AsyncThunkOptions< ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = { /** * A method to control whether the asyncThunk should be executed. Has access to the * `arg`, `api.getState()` and `api.extra` arguments. * * @returns `false` if it should be skipped */ condition?( arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'> ): MaybePromise<boolean | undefined>; /** * If `condition` returns `false`, the asyncThunk will be skipped. * This option allows you to control whether a `rejected` action with `meta.condition == false` * will be dispatched or not. * * @default `false` */ dispatchConditionRejection?: boolean; serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>; /** * A function to use when generating the `requestId` for the request sequence. * * @default `nanoid` */ idGenerator?: (arg: ThunkArg) => string;} & IsUnknown< GetPendingMeta<ThunkApiConfig>, { /** * A method to generate additional properties to be added to `meta` of the pending action. * * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users. * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload */ getPendingMeta?( base: { arg: ThunkArg; requestId: string; }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'> ): GetPendingMeta<ThunkApiConfig>; }, { /** * A method to generate additional properties to be added to `meta` of the pending action. */ getPendingMeta( base: { arg: ThunkArg; requestId: string; }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'> ): GetPendingMeta<ThunkApiConfig>; }>;
Options object for
createAsyncThunk
.Modifiers
@public
type AsyncThunkPayloadCreator
type AsyncThunkPayloadCreator< Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = ( arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;
A type describing the
payloadCreator
argument tocreateAsyncThunk
. Might be useful for wrappingcreateAsyncThunk
in custom abstractions.Modifiers
@public
type AsyncThunkPayloadCreatorReturnValue
type AsyncThunkPayloadCreatorReturnValue< Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise< | IsUnknown< GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>> > | RejectWithValue< GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig> >>;
A type describing the return value of the
payloadCreator
argument tocreateAsyncThunk
. Might be useful for wrappingcreateAsyncThunk
in custom abstractions.Modifiers
@public
type AutoBatchOptions
type AutoBatchOptions = | { type: 'tick'; } | { type: 'timer'; timeout: number; } | { type: 'raf'; } | { type: 'callback'; queueNotification: (notify: () => void) => void; };
type CaseReducer
type CaseReducer<S = any, A extends Action = AnyAction> = ( state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;
A *case reducer* is a reducer function for a specific action type. Case reducers can be composed to full reducers using
createReducer()
.Unlike a normal Redux reducer, a case reducer is never called with an
undefined
state to determine the initial state. Instead, the initial state is explicitly specified as an argument tocreateReducer()
.In addition, a case reducer can choose to mutate the passed-in
state
value directly instead of returning a new state. This does not actually cause the store state to be mutated directly; instead, thanks to [immer](https://github.com/mweststrate/immer), the mutations are translated to copy operations that result in a new state.Modifiers
@public
type CaseReducerActions
type CaseReducerActions< CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = { [Type in keyof CaseReducers]: CaseReducers[Type] extends { prepare: any; } ? ActionCreatorForCaseReducerWithPrepare< CaseReducers[Type], SliceActionType<SliceName, Type> > : ActionCreatorForCaseReducer< CaseReducers[Type], SliceActionType<SliceName, Type> >;};
Derives the slice's
actions
property from thereducers
optionsModifiers
@public
type CaseReducers
type CaseReducers<S, AS extends Actions> = { [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void;};
A mapping from action types to case reducers for
createReducer()
.Modifiers
@public
Deprecated
This should not be used manually - it is only used for internal inference purposes and using it manually would lead to type erasure. It might be removed in the future.
type CaseReducerWithPrepare
type CaseReducerWithPrepare<State, Action extends PayloadAction> = { reducer: CaseReducer<State, Action>; prepare: PrepareAction<Action['payload']>;};
A CaseReducer with a
prepare
method.Modifiers
@public
type Comparer
type Comparer<T> = (a: T, b: T) => number;
Modifiers
@public
type ConfigureEnhancersCallback
type ConfigureEnhancersCallback<E extends Enhancers = Enhancers> = ( defaultEnhancers: EnhancerArray<[StoreEnhancer<{}, {}>]>) => E;
Callback function type, to be used in
ConfigureStoreOptions.enhancers
Modifiers
@public
type EnhancedStore
type EnhancedStore< S = any, A extends Action = AnyAction, M extends Middlewares<S> = Middlewares<S>, E extends Enhancers = Enhancers> = ToolkitStore<S & ExtractStateExtensions<E>, A, M> & ExtractStoreExtensions<E>;
A Redux store returned by
configureStore()
. Supports dispatching side-effectful _thunks_ in addition to plain actions.Modifiers
@public
type EntityId
type EntityId = number | string;
Modifiers
@public
type ForkedTaskExecutor
type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>;
Modifiers
@public
type IdSelector
type IdSelector<T> = (model: T) => EntityId;
Modifiers
@public
type ListenerEffect
type ListenerEffect< Action extends AnyAction, State, Dispatch extends ReduxDispatch<AnyAction>, ExtraArgument = unknown> = ( action: Action, api: ListenerEffectAPI<State, Dispatch, ExtraArgument>) => void | Promise<void>;
Modifiers
@public
type ListenerMiddleware
type ListenerMiddleware< State = unknown, Dispatch extends ThunkDispatch<State, unknown, AnyAction> = ThunkDispatch< State, unknown, AnyAction >, ExtraArgument = unknown> = Middleware< { (action: ReduxAction<'listenerMiddleware/add'>): UnsubscribeListener; }, State, Dispatch>;
Modifiers
@public
type PayloadAction
type PayloadAction<P = void, T extends string = string, M = never, E = never> = { payload: P; type: T;} & ([M] extends [never] ? {} : { meta: M; }) & ([E] extends [never] ? {} : { error: E; });
An action with a string type and an associated payload. This is the type of action returned by
createAction()
action creators.P The type of the action's payload. T the type used for the action type. M The type of the action's meta (optional) E The type of the action's error (optional)
Modifiers
@public
type PayloadActionCreator
type PayloadActionCreator< P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided< PA, _ActionCreatorWithPreparedPayload<PA, T>, IsAny< P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable< P, ActionCreatorWithNonInferrablePayload<T>, IfVoid< P, ActionCreatorWithoutPayload<T>, IfMaybeUndefined< P, ActionCreatorWithOptionalPayload<P, T>, ActionCreatorWithPayload<P, T> > > > >>;
An action creator that produces actions with a
payload
attribute.Modifiers
@public
type PrepareAction
type PrepareAction<P> = | ((...args: any[]) => { payload: P; }) | ((...args: any[]) => { payload: P; meta: any; }) | ((...args: any[]) => { payload: P; error: any; }) | ((...args: any[]) => { payload: P; meta: any; error: any; });
A "prepare" method to be used as the second parameter of
createAction
. Takes any number of arguments and returns a Flux Standard Action without type (will be added later) that *must* contain a payload (might be undefined).Modifiers
@public
type SliceActionCreator
type SliceActionCreator<P> = PayloadActionCreator<P>;
An action creator attached to a slice.
Modifiers
@public
Deprecated
please use PayloadActionCreator directly
type SliceCaseReducers
type SliceCaseReducers<State> = { [K: string]: | CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>;};
The type describing a slice's
reducers
option.Modifiers
@public
type TaskCancelled
type TaskCancelled = { readonly status: 'cancelled'; readonly error: TaskAbortError;};
Modifiers
@public
type TaskRejected
type TaskRejected = { readonly status: 'rejected'; readonly error: unknown;};
Modifiers
@public
type TaskResolved
type TaskResolved<T> = { readonly status: 'ok'; readonly value: T;};
Modifiers
@public
type TaskResult
type TaskResult<Value> = TaskResolved<Value> | TaskRejected | TaskCancelled;
Modifiers
@public
type TSHelpersExtractDispatchExtensions
type ExtractDispatchExtensions<M> = M extends MiddlewareArray<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;
type TypedAddListener
type TypedAddListener< State, Dispatch extends ReduxDispatch<AnyAction> = ThunkDispatch< State, unknown, AnyAction >, ExtraArgument = unknown, Payload = ListenerEntry<State, Dispatch>, T extends string = 'listenerMiddleware/add'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, State, Dispatch, ExtraArgument>;
A "pre-typed" version of
addListenerAction
, so the listener args are well-typedModifiers
@public
type TypedRemoveListener
type TypedRemoveListener< State, Dispatch extends ReduxDispatch<AnyAction> = ThunkDispatch< State, unknown, AnyAction >, Payload = ListenerEntry<State, Dispatch>, T extends string = 'listenerMiddleware/remove'> = BaseActionCreator<Payload, T> & AddListenerOverloads< PayloadAction<Payload, T>, State, Dispatch, any, UnsubscribeListenerOptions >;
A "pre-typed" version of
removeListenerAction
, so the listener args are well-typedModifiers
@public
type TypedStartListening
type TypedStartListening< State, Dispatch extends ReduxDispatch<AnyAction> = ThunkDispatch< State, unknown, AnyAction >, ExtraArgument = unknown> = AddListenerOverloads<UnsubscribeListener, State, Dispatch, ExtraArgument>;
A "pre-typed" version of
middleware.startListening
, so the listener args are well-typedModifiers
@public
type TypedStopListening
type TypedStopListening< State, Dispatch extends ReduxDispatch<AnyAction> = ThunkDispatch< State, unknown, AnyAction >> = RemoveListenerOverloads<State, Dispatch>;
A "pre-typed" version of
middleware.stopListening
, so the listener args are well-typedModifiers
@public
type UnsubscribeListener
type UnsubscribeListener = (unsubscribeOptions?: UnsubscribeListenerOptions) => void;
Modifiers
@public
type Update
type Update<T> = { id: EntityId; changes: Partial<T>;};
Modifiers
@public
type ValidateSliceCaseReducers
type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & { [T in keyof ACR]: ACR[T] extends { reducer(s: S, action?: infer A): any; } ? { prepare(...a: never[]): Omit<A, 'type'>; } : {};};
Used on a SliceCaseReducers object. Ensures that if a CaseReducer is a
CaseReducerWithPrepare
, that thereducer
and theprepare
function use the same type ofpayload
.Might do additional such checks in the future.
This type is only ever useful if you want to write your own wrapper around
createSlice
. Please don't use it otherwise!Modifiers
@public
Package Files (24)
- dist/actionCreatorInvariantMiddleware.d.ts
- dist/autoBatchEnhancer.d.ts
- dist/configureStore.d.ts
- dist/createAction.d.ts
- dist/createAsyncThunk.d.ts
- dist/createDraftSafeSelector.d.ts
- dist/createReducer.d.ts
- dist/createSlice.d.ts
- dist/devtoolsExtension.d.ts
- dist/entities/create_adapter.d.ts
- dist/entities/models.d.ts
- dist/getDefaultMiddleware.d.ts
- dist/immutableStateInvariantMiddleware.d.ts
- dist/index.d.ts
- dist/isPlainObject.d.ts
- dist/listenerMiddleware/exceptions.d.ts
- dist/listenerMiddleware/index.d.ts
- dist/listenerMiddleware/types.d.ts
- dist/mapBuilders.d.ts
- dist/matchers.d.ts
- dist/nanoid.d.ts
- dist/serializableStateInvariantMiddleware.d.ts
- dist/tsHelpers.d.ts
- dist/utils.d.ts
Dependencies (4)
Dev Dependencies (49)
- @microsoft/api-extractor
- @phryneas/ts-version
- @size-limit/preset-small-lib
- @testing-library/react
- @testing-library/user-event
- @types/convert-source-map
- @types/jest
- @types/json-stringify-safe
- @types/nanoid
- @types/node
- @types/query-string
- @types/react
- @types/react-dom
- @types/yargs
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- axios
- console-testing-library
- convert-source-map
- esbuild
- eslint
- eslint-config-prettier
- eslint-config-react-app
- eslint-plugin-flowtype
- eslint-plugin-import
- eslint-plugin-jsx-a11y
- eslint-plugin-prettier
- eslint-plugin-react
- eslint-plugin-react-hooks
- fs-extra
- invariant
- jest
- json-stringify-safe
- magic-string
- merge-source-map
- msw
- node-fetch
- prettier
- query-string
- rimraf
- rollup
- rollup-plugin-strip-code
- size-limit
- source-map
- terser
- ts-jest
- tslib
- typescript
- yargs
Peer Dependencies (2)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@reduxjs/toolkit
.
- Markdown[](https://www.jsdocs.io/package/@reduxjs/toolkit)
- HTML<a href="https://www.jsdocs.io/package/@reduxjs/toolkit"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 9776 ms. - Missing or incorrect documentation? Open an issue for this package.