| 1 |
import type { Middleware } from 'redux' |
| 2 |
import { isActionCreator as isRTKAction } from './createAction' |
| 3 |
|
| 4 |
export interface ActionCreatorInvariantMiddlewareOptions { |
| 5 |
/** |
| 6 |
* The function to identify whether a value is an action creator. |
| 7 |
* The default checks for a function with a static type property and match method. |
| 8 |
*/ |
| 9 |
isActionCreator?: (action: unknown) => action is Function & { type?: unknown } |
| 10 |
} |
| 11 |
|
| 12 |
export function getMessage(type?: unknown) { |
| 13 |
const splitType = type ? `${type}`.split('/') : [] |
| 14 |
const actionName = splitType[splitType.length - 1] || 'actionCreator' |
| 15 |
return `Detected an action creator with type "${ |
| 16 |
type || 'unknown' |
| 17 |
}" being dispatched. |
| 18 |
Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${actionName}())\` instead of \`dispatch(${actionName})\`. This is necessary even if the action has no payload.` |
| 19 |
} |
| 20 |
|
| 21 |
export function createActionCreatorInvariantMiddleware( |
| 22 |
options: ActionCreatorInvariantMiddlewareOptions = {}, |
| 23 |
): Middleware { |
| 24 |
if (process.env.NODE_ENV === 'production') { |
| 25 |
return () => (next) => (action) => next(action) |
| 26 |
} |
| 27 |
const { isActionCreator = isRTKAction } = options |
| 28 |
return () => (next) => (action) => { |
| 29 |
if (isActionCreator(action)) { |
| 30 |
console.warn(getMessage(action.type)) |
| 31 |
} |
| 32 |
return next(action) |
| 33 |
} |
| 34 |
} |