Skip to content

Commit

Permalink
use setState in patchState; remove isInitialized check; improve test …
Browse files Browse the repository at this point in the history
…case with callback
  • Loading branch information
markostanimirovic committed Nov 17, 2020
1 parent 887e074 commit 2c2fc55
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
6 changes: 4 additions & 2 deletions modules/component-store/spec/component-store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,11 +569,13 @@ describe('Component Store', () => {
it(
'with a value based on the previous state',
marbles((m) => {
componentStore.patchState(() => ({ value2: { foo: 'fooBar' } }));
componentStore.patchState((state) => ({
value2: { foo: `${state.value2.foo}2` },
}));

m.expect(componentStore.state$).toBeObservable(
m.hot('s', {
s: { ...INIT_STATE, value2: { foo: 'fooBar' } },
s: { ...INIT_STATE, value2: { foo: 'bar2' } },
})
);
})
Expand Down
18 changes: 9 additions & 9 deletions modules/component-store/src/component-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,17 +166,17 @@ export class ComponentStore<T extends object> implements OnDestroy {
patchState(
partialStateOrUpdaterFn: Partial<T> | ((state: T) => Partial<T>)
): void {
if (!this.isInitialized) {
throw new Error(this.notInitializedErrorMessage);
}
this.setState((state) => {
const patchedState =
typeof partialStateOrUpdaterFn === 'function'
? partialStateOrUpdaterFn(state)
: partialStateOrUpdaterFn;

const updaterFn = (state: T) => ({
...state,
...(typeof partialStateOrUpdaterFn === 'function'
? partialStateOrUpdaterFn(state)
: partialStateOrUpdaterFn),
return {
...state,
...patchedState,
};
});
this.updater(updaterFn)();
}

protected get(): T;
Expand Down

0 comments on commit 2c2fc55

Please sign in to comment.