Skip to content

Create standardised methods of modifying reducer handler context. #3872

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 132 additions & 18 deletions packages/toolkit/src/createSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import type {
ReducerWithInitialState,
} from './createReducer'
import { createReducer } from './createReducer'
import type { ActionReducerMapBuilder } from './mapBuilders'
import type { ActionReducerMapBuilder, TypedActionCreator } from './mapBuilders'
import { executeReducerBuilderCallback } from './mapBuilders'
import type { Id, Tail } from './tsHelpers'
import type { Id, Tail, TypeGuard } from './tsHelpers'
import type { InjectConfig } from './combineSlices'
import type {
AsyncThunk,
Expand Down Expand Up @@ -630,6 +630,43 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {
sliceMatchers: [],
}

const contextMethods: ReducerHandlingContextMethods<State> = {
addCase(
typeOrActionCreator: string | TypedActionCreator<any>,
reducer: CaseReducer<State>
) {
const type =
typeof typeOrActionCreator === 'string'
? typeOrActionCreator
: typeOrActionCreator.type
if (!type) {
throw new Error(
'`context.addCase` cannot be called with an empty action type'
)
}
if (type in context.sliceCaseReducersByType) {
throw new Error(
'`context.addCase` cannot be called with two reducers for the same action type: ' +
type
)
}
context.sliceCaseReducersByType[type] = reducer
return contextMethods
},
addMatcher(matcher, reducer) {
context.sliceMatchers.push({ matcher, reducer })
return contextMethods
},
exposeAction(name, actionCreator) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the expose methods could also throw errors if there's name conflicts

context.actionCreators[name] = actionCreator
return contextMethods
},
exposeCaseReducer(name, reducer) {
context.sliceCaseReducersByName[name] = reducer
return contextMethods
},
}

reducerNames.forEach((reducerName) => {
const reducerDefinition = reducers[reducerName]
const reducerDetails: ReducerDetails = {
Expand All @@ -641,14 +678,14 @@ export function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {
handleThunkCaseReducerDefinition(
reducerDetails,
reducerDefinition,
context,
contextMethods,
cAT
)
} else {
handleNormalReducerDefinition<State>(
reducerDetails,
reducerDefinition,
context
contextMethods
)
}
})
Expand Down Expand Up @@ -803,9 +840,84 @@ interface ReducerHandlingContext<State> {
actionCreators: Record<string, Function>
}

interface ReducerHandlingContextMethods<State> {
/**
* Adds a case reducer to handle a single action type.
* @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
* @param reducer - The actual case reducer function.
*/
addCase<ActionCreator extends TypedActionCreator<string>>(
actionCreator: ActionCreator,
reducer: CaseReducer<State, ReturnType<ActionCreator>>
): ReducerHandlingContextMethods<State>
/**
* Adds a case reducer to handle a single action type.
* @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
* @param reducer - The actual case reducer function.
*/
addCase<Type extends string, A extends Action<Type>>(
type: Type,
reducer: CaseReducer<State, A>
): ReducerHandlingContextMethods<State>

/**
* Allows you to match incoming actions against your own filter function instead of only the `action.type` property.
* @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 to `builder.addCase` and before any calls to `builder.addDefaultCase`.
* @param 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
* @param reducer - The actual case reducer function.
*
*/
addMatcher<A>(
matcher: TypeGuard<A>,
reducer: CaseReducer<State, A extends Action ? A : A & Action>
): ReducerHandlingContextMethods<State>
/**
* Add an action to be exposed under the final `slice.actions` key.
* @param name The key to be exposed as.
* @param actionCreator The action to expose.
* @example
* context.exposeAction("addPost", createAction<Post>("addPost"));
*
* export const { addPost } = slice.actions
*
* dispatch(addPost(post))
*/
exposeAction(
name: string,
actionCreator: Function
): ReducerHandlingContextMethods<State>
/**
* Add a case reducer to be exposed under the final `slice.caseReducers` key.
* @param name The key to be exposed as.
* @param reducer The reducer to expose.
* @example
* context.exposeCaseReducer("addPost", (state, action: PayloadAction<Post>) => {
* state.push(action.payload)
* })
*
* slice.caseReducers.addPost([], addPost(post))
*/
exposeCaseReducer(
name: string,
reducer:
| CaseReducer<State, any>
| Pick<
AsyncThunkSliceReducerDefinition<State, any, any, any>,
'fulfilled' | 'rejected' | 'pending' | 'settled'
>
): ReducerHandlingContextMethods<State>
}

interface ReducerDetails {
/** The key the reducer was defined under */
reducerName: string
/** The predefined action type, i.e. `${slice.name}/${reducerName}` */
type: string
/** Whether create. notation was used when defining reducers */
createNotation: boolean
}

Expand Down Expand Up @@ -852,7 +964,7 @@ function handleNormalReducerDefinition<State>(
maybeReducerWithPrepare:
| CaseReducer<State, { payload: any; type: string }>
| CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>,
context: ReducerHandlingContext<State>
context: ReducerHandlingContextMethods<State>
) {
let caseReducer: CaseReducer<State, any>
let prepareCallback: PrepareAction<any> | undefined
Expand All @@ -870,11 +982,13 @@ function handleNormalReducerDefinition<State>(
} else {
caseReducer = maybeReducerWithPrepare
}
context.sliceCaseReducersByName[reducerName] = caseReducer
context.sliceCaseReducersByType[type] = caseReducer
context.actionCreators[reducerName] = prepareCallback
? createAction(type, prepareCallback)
: createAction(type)
context
.addCase(type, caseReducer)
.exposeCaseReducer(reducerName, caseReducer)
.exposeAction(
reducerName,
prepareCallback ? createAction(type, prepareCallback) : createAction(type)
)
}

function isAsyncThunkSliceReducerDefinition<State>(
Expand All @@ -894,7 +1008,7 @@ function isCaseReducerWithPrepareDefinition<State>(
function handleThunkCaseReducerDefinition<State>(
{ type, reducerName }: ReducerDetails,
reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>,
context: ReducerHandlingContext<State>,
context: ReducerHandlingContextMethods<State>,
cAT: typeof _createAsyncThunk | undefined
) {
if (!cAT) {
Expand All @@ -906,27 +1020,27 @@ function handleThunkCaseReducerDefinition<State>(
const { payloadCreator, fulfilled, pending, rejected, settled, options } =
reducerDefinition
const thunk = cAT(type, payloadCreator, options as any)
context.actionCreators[reducerName] = thunk
context.exposeAction(reducerName, thunk)

if (fulfilled) {
context.sliceCaseReducersByType[thunk.fulfilled.type] = fulfilled
context.addCase(thunk.fulfilled, fulfilled)
}
if (pending) {
context.sliceCaseReducersByType[thunk.pending.type] = pending
context.addCase(thunk.pending, pending)
}
if (rejected) {
context.sliceCaseReducersByType[thunk.rejected.type] = rejected
context.addCase(thunk.rejected, rejected)
}
if (settled) {
context.sliceMatchers.push({ matcher: thunk.settled, reducer: settled })
context.addMatcher(thunk.settled, settled)
}

context.sliceCaseReducersByName[reducerName] = {
context.exposeCaseReducer(reducerName, {
fulfilled: fulfilled || noop,
pending: pending || noop,
rejected: rejected || noop,
settled: settled || noop,
}
})
}

function noop() {}