Skip to content

Commit

Permalink
[@xstate/store] Fix emitted event type being overridden (#5197)
Browse files Browse the repository at this point in the history
* Add failing test

* Fix

* Changeset

* Remove console log
  • Loading branch information
davidkpiano authored Feb 14, 2025
1 parent a4f9ca3 commit 5e05d59
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/lazy-dolphins-sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@xstate/store': patch
---

The emitted event type can no longer be accidentally overridden in the emitted event payload. See #5196 for the issue.
4 changes: 2 additions & 2 deletions packages/xstate-store/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,8 +420,8 @@ export function createStoreTransition<
get: (_, eventType: string) => {
return (payload: any) => {
effects.push({
type: eventType,
...payload
...payload,
type: eventType
});
};
}
Expand Down
49 changes: 49 additions & 0 deletions packages/xstate-store/test/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,3 +481,52 @@ it('works with typestates', () => {
context.data satisfies null;
}
});

it('the emit type is not overridden by the payload', () => {
const spy = jest.fn();
type Context = {
drawer?: Drawer | null;
};

type Drawer = {
id: string;
};

const context: Context = {
drawer: null
};

const drawersBridgeStore = createStore({
emits: {
drawerOpened: (_payload: { drawer: Drawer }) => {
// ...
}
},
context,
on: {
openDrawer: (context, event: { drawer: Drawer }, enqueue) => {
enqueue.emit.drawerOpened(event);

return {
...context,
drawer: event.drawer
};
}
}
});

drawersBridgeStore.on('drawerOpened', (event) => {
// expect to be called here
spy(event);
});

drawersBridgeStore.send({
type: 'openDrawer',
drawer: { id: 'a' }
});

expect(spy).toHaveBeenCalledWith({
type: 'drawerOpened',
drawer: { id: 'a' }
});
});

0 comments on commit 5e05d59

Please sign in to comment.