Skip to content

Commit

Permalink
Fix subscribe path breaking past 2
Browse files Browse the repository at this point in the history
  • Loading branch information
kalvinpearce committed Nov 28, 2019
1 parent 6515e86 commit b19bf2f
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 4 deletions.
53 changes: 52 additions & 1 deletion src/index.subscribe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,22 @@ const initialState = {
first: 'john',
last: 'doe',
},
obj: {
thing: {
a: 1,
b: [
{
hello: 0,
},
{
hello: 1,
},
{
hello: 2,
},
],
},
},
};

describe('subscribe', () => {
Expand Down Expand Up @@ -39,7 +55,22 @@ describe('subscribe', () => {
expect(mockSub).toBeCalledTimes(1);
});

it('calls subscribed event when relevant state is changed with different param versions', () => {
it('calls even deeper property event when relevant state is changed', () => {
/* Setup */
const { updateState, subscribe } = createStore(initialState);
const mockSub = jest.fn();
subscribe(['obj', 'thing', 'b', 0, 'hello'], mockSub);

/* Action */
updateState(d => {
d.obj.thing.b[0].hello = 10;
});

/* Test */
expect(mockSub).toBeCalledTimes(1);
});

it('calls event when relevant state is changed with different param versions', () => {
/* Setup */
const { updateState, subscribe } = createStore(initialState);
const mockSub = jest.fn();
Expand Down Expand Up @@ -140,6 +171,26 @@ describe('subscribe', () => {
expect(mockSub).toBeCalledTimes(1);
});

it('calls event once when parent & child changes at same time', () => {
/* Setup */
const { updateState, subscribe } = createStore(initialState);
const mockSub = jest.fn();
subscribe(['name', 'first'], mockSub);

/* Action */
updateState(d => {
d.name = {
first: 'new',
last: 'changed',
};

d.name.first = 'newer';
});

/* Test */
expect(mockSub).toBeCalledTimes(1);
});

it("it doesn't call event after unsubscribe", () => {
/* Setup */
const { updateState, subscribe } = createStore(initialState);
Expand Down
6 changes: 3 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,11 @@ export const createStore = <State>(initialState: State) => {
* @param callback function to run when state piece changes
* @returns function to unsubscribe the callback
*/
const subscribe = <PPath extends Path<State, PPath>>(
const subscribe = <PPath extends Path<S, PPath>, S extends State = State>(
statePath: PPath,
callback: (state: PathValue<State, PPath> | State[keyof State]) => void,
callback: (state: PathValue<S, PPath> | S[keyof S]) => void,
) => {
const fn = () => callback(getFromPath(state, statePath));
const fn = () => callback(getFromPath(state as S, statePath));

const key = Array.isArray(statePath)
? statePath.join('.')
Expand Down

0 comments on commit b19bf2f

Please sign in to comment.