Skip to content

Commit da2f1bc

Browse files
committed
feat: provide parent state as second parameter to update function in wrapReducerWithFormStateUpdate
1 parent 15cc17a commit da2f1bc

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/reducer.spec.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,30 @@ describe(wrapReducerWithFormStateUpdate.name, () => {
237237
expect(resultState).toBe(initialState);
238238
});
239239

240+
it('should pass the state as the second parameter to the update function', () => {
241+
const wrappedReducer = wrapReducerWithFormStateUpdate(reducer, s => s.control, (s, state) => {
242+
expect(state).toBe(initialState);
243+
return s;
244+
});
245+
246+
wrappedReducer(undefined, { type: '' });
247+
});
248+
249+
it('should call the update function after the reducer', () => {
250+
let reducerWasCalled = false;
251+
const reducer = (s = initialState) => {
252+
reducerWasCalled = true;
253+
return s;
254+
};
255+
256+
const wrappedReducer = wrapReducerWithFormStateUpdate(reducer, s => s.group, s => {
257+
expect(reducerWasCalled).toBe(true);
258+
return s;
259+
});
260+
261+
wrappedReducer(undefined, { type: '' });
262+
});
263+
240264
it('should work with createReducer', () => {
241265
const state = {
242266
prop: 'value',

src/reducer.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,19 +109,22 @@ export function onNgrxForms<TState = any>(): { reducer: ActionReducer<TState>; t
109109
* This function wraps a reducer and returns another reducer that first calls
110110
* the given reducer and then calls the given update function for the form state
111111
* that is specified by the form state locator function.
112+
*
113+
* The update function is passed the form state and the updated containing state
114+
* as parameters.
112115
*/
113116
export function wrapReducerWithFormStateUpdate<TState, TFormState extends AbstractControlState<any>>(
114117
reducer: ActionReducer<TState>,
115118
formStateLocator: (state: TState) => TFormState,
116-
updateFn: (formState: TFormState) => TFormState,
119+
updateFn: (formState: TFormState, state: TState) => TFormState,
117120
): ActionReducer<TState> {
118121
return (state, action) => {
119122
const updatedState = reducer(state, action);
120123

121124
const formState = formStateLocator(updatedState);
122125
const formStateKey = Object.keys(updatedState).find(key => updatedState[key as keyof TState] as any === formState)!;
123126

124-
const updatedFormState = updateFn(formState);
127+
const updatedFormState = updateFn(formState, updatedState);
125128

126129
if (updatedFormState === formState) {
127130
return updatedState;

0 commit comments

Comments
 (0)