1 import type { Action, PayloadActionCreator, PrepareAction } from '@reduxjs/toolkit';
2 import { createAction } from '@reduxjs/toolkit';
4 import type { OptimisticMatcherResult } from '../types';
7 * Wraps the @reduxjs/toolkit createAction helper utility.
8 * Requires passing an additional parameter to derive an
9 * optimistic identifier from the resulting action.
11 * Adds a static property `actionCreator::matchOptimistic`
12 * method on the returned action creator which wraps the
13 * default `actionCreator::match` function but will return
14 * the derived optimistic id when a match arises. This is
15 * mainly to make it easier to write optimistic matchers.
17 export const createOptimisticAction = <
18 PA extends PrepareAction<any>,
19 T extends string = string,
20 OptimisticAction = ReturnType<PayloadActionCreator<ReturnType<PA>['payload'], T, PA>>,
24 optimisticIdFactory: (action: OptimisticAction) => string
26 const actionCreator = createAction(type, prepare) as PayloadActionCreator<ReturnType<PA>['payload'], T, PA> & {
27 optimisticMatch: (action: Action) => OptimisticMatcherResult;
30 actionCreator.optimisticMatch = (action: Action) =>
31 actionCreator.match(action) && optimisticIdFactory(action as OptimisticAction);