Skip to content

Commit

Permalink
✅ test: Functions are preserved between patches
Browse files Browse the repository at this point in the history
  • Loading branch information
joebobmiles committed Jul 12, 2021
1 parent 9935448 commit f8253b8
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
46 changes: 46 additions & 0 deletions src/patching.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,4 +524,50 @@ describe("patchStore", () =>

expect(store.getState().foo[0].baz).toBeUndefined();
});

it("Preserves functions contained in the store.", () =>
{
type State =
{
"count": number,
"increment": () => void,

"room": {
"users": string[],
"join": (user: string) => void,
},
};

const store = create<State>((set) =>
({
"count": 1,
"increment": () =>
set((state) =>
({ ...state, "count": state.count + 1, })),
"room": {
"users": [],
"join": (user) =>
set((state) =>
({
...state,
"room": {
...state.room,
"users": [ ...state.room.users, user ],
},
})),
},
}));

const update = {
"count": 3,
"room": {
"users": [],
},
};

patchStore(store, update);

expect(store.getState().increment).not.toBeUndefined();
expect(store.getState().room.join).not.toBeUndefined();
});
});
15 changes: 14 additions & 1 deletion src/patching.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ export const patchStore = <S extends State>(
{
const changes = getChangeList(oldState, newState);

return changes.reduce(
const p: any = changes.reduce(
(state, [ type, property, value ]) =>
{
switch (type)
Expand Down Expand Up @@ -199,6 +199,19 @@ export const patchStore = <S extends State>(
},
{}
);

return {
...Object.entries(oldState).reduce(
(o, [ property, value ]) =>
(
value instanceof Function
? { ...o, [property]: value, }
: o
),
{}
),
...p,
};
};

store.setState(
Expand Down

0 comments on commit f8253b8

Please sign in to comment.