Skip to content
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

RFC: Add predicate to createSlice reducers. #366

Closed
Closed
Show file tree
Hide file tree
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
17 changes: 14 additions & 3 deletions etc/redux-toolkit.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,10 @@ export type CaseReducer<S = any, A extends Action = AnyAction> = (state: Draft<S
// @public
export type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>> = {
[Type in keyof CaseReducers]: CaseReducers[Type] extends {
prepare: any;
} ? ActionCreatorForCaseReducerWithPrepare<CaseReducers[Type]> : ActionCreatorForCaseReducer<CaseReducers[Type]>;
prepare: AnyFunction;
} ? ActionCreatorForCaseReducerWithPrepare<CaseReducers[Type]> : CaseReducers[Type] extends {
reducer: AnyFunction;
} ? ActionCreatorForCaseReducer<CaseReducers[Type]['reducer']> : ActionCreatorForCaseReducer<CaseReducers[Type]>;
};

// @public @deprecated
Expand All @@ -74,7 +76,8 @@ export type CaseReducers<S, AS extends Actions> = {
// @public
export type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
reducer: CaseReducer<State, Action>;
prepare: PrepareAction<Action['payload']>;
prepare?: PrepareAction<Action['payload']>;
predicate?: Predicate<State, Action>;
};

// @public
Expand Down Expand Up @@ -202,10 +205,18 @@ export { ThunkAction }
// @public
export type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & {
[T in keyof ACR]: ACR[T] extends {
prepare: AnyFunction;
reducer(s: S, action?: infer A): any;
} ? {
prepare(...a: never[]): Omit<A, 'type'>;
} : {};
} & {
[T in keyof ACR]: ACR[T] extends {
predicate: AnyFunction;
reducer(s: S, action?: infer A): any;
} ? {
predicate: Predicate<S, A>;
} : {};
};


Expand Down
62 changes: 62 additions & 0 deletions src/createSlice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,65 @@ describe('createSlice', () => {
})
})
})

test('createSlice with predicate for reducer', () => {
const slice = createSlice({
name: 'test',
initialState: {
status: 'idle'
} as { status: 'working' | 'idle'; workItem?: string },
reducers: {
startWork: {
predicate: state => state.status === 'idle',
reducer(state, action: PayloadAction<string>) {
state.status = 'working'
state.workItem = action.payload
}
},
finishWork: {
predicate: state => state.status === 'working',
reducer(state) {
state.status = 'idle'
state.workItem = undefined
}
}
}
})

expect(slice.reducer({ status: 'idle' }, slice.actions.startWork('workItem')))
.toMatchInlineSnapshot(`
Object {
"status": "working",
"workItem": "workItem",
}
`)
expect(
slice.reducer(
{ status: 'working', workItem: 'shouldNotChange' },
slice.actions.startWork('workItem')
)
).toMatchInlineSnapshot(`
Object {
"status": "working",
"workItem": "shouldNotChange",
}
`)
expect(
slice.reducer(
{ status: 'idle', workItem: 'shouldNotChange' },
slice.actions.finishWork()
)
).toMatchInlineSnapshot(`
Object {
"status": "idle",
"workItem": "shouldNotChange",
}
`)
expect(slice.reducer({ status: 'working' }, slice.actions.finishWork()))
.toMatchInlineSnapshot(`
Object {
"status": "idle",
"workItem": undefined,
}
`)
})
43 changes: 38 additions & 5 deletions src/createSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
ActionReducerMapBuilder,
executeReducerBuilderCallback
} from './mapBuilders'
import { Omit } from './tsHelpers'
import { Omit, AnyFunction } from './tsHelpers'
import { Draft } from 'immer'

/**
* An action creator atttached to a slice.
Expand Down Expand Up @@ -100,9 +101,15 @@ export interface CreateSliceOptions<
*/
export type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
reducer: CaseReducer<State, Action>
prepare: PrepareAction<Action['payload']>
prepare?: PrepareAction<Action['payload']>
predicate?: Predicate<State, Action>
}

export type Predicate<State, Action> = (
state: Draft<State>,
action: Action
) => boolean

/**
* The type describing a slice's `reducers` option.
*
Expand All @@ -120,8 +127,12 @@ export type SliceCaseReducers<State> = {
* @public
*/
export type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>> = {
[Type in keyof CaseReducers]: CaseReducers[Type] extends { prepare: any }
[Type in keyof CaseReducers]: CaseReducers[Type] extends {
prepare: AnyFunction
}
? ActionCreatorForCaseReducerWithPrepare<CaseReducers[Type]>
: CaseReducers[Type] extends { reducer: AnyFunction }
? ActionCreatorForCaseReducer<CaseReducers[Type]['reducer']>
: ActionCreatorForCaseReducer<CaseReducers[Type]>
}

Expand Down Expand Up @@ -189,12 +200,23 @@ export type ValidateSliceCaseReducers<
> = ACR &
{
[T in keyof ACR]: ACR[T] extends {
prepare: AnyFunction
reducer(s: S, action?: infer A): any
}
? {
prepare(...a: never[]): Omit<A, 'type'>
}
: {}
} &
{
[T in keyof ACR]: ACR[T] extends {
predicate: AnyFunction
reducer(s: S, action?: infer A): any
}
? {
predicate: Predicate<S, A>
}
: {}
}

function getType(slice: string, actionKey: string): string {
Expand Down Expand Up @@ -243,8 +265,19 @@ export function createSlice<
let prepareCallback: PrepareAction<any> | undefined

if ('reducer' in maybeReducerWithPrepare) {
caseReducer = maybeReducerWithPrepare.reducer
prepareCallback = maybeReducerWithPrepare.prepare
const { reducer, predicate, prepare } = maybeReducerWithPrepare
if (predicate) {
caseReducer = (state, action) => {
if (predicate(state, action)) {
return reducer(state, action)
}
}
} else {
caseReducer = reducer
}
if (prepare) {
prepareCallback = prepare
}
} else {
caseReducer = maybeReducerWithPrepare
}
Expand Down
2 changes: 2 additions & 0 deletions src/tsHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,5 @@ type UnionToIntersection<U> = (U extends any
: never

export type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>

export type AnyFunction = (...args: any[]) => any