Skip to content

Commit dcb4cf4

Browse files
committed
~ Document and test emit-less actions
1 parent 74bbc95 commit dcb4cf4

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,43 @@ Clicking `Reset` will put the `counter` back to `0`.
321321
> You can call `$reset()` without a field parameter to reset _all_ state in the
322322
> store.
323323
324+
## Nested Actions
325+
326+
Beginning an action name with a `$` will mean it won't emit subscription
327+
announcements at the end of the action. This can be useful if you wish to use
328+
actions from other actions.
329+
330+
```tsx
331+
// store.ts
332+
import { TwoAndEight } from '2n8'
333+
334+
class Store extends TwoAndEight {
335+
counter = 0
336+
face: '🫤' | '🥸' = '🫤'
337+
338+
$repeatedAction = () => {
339+
this.counter++
340+
// Will not emit when called but state will change.
341+
}
342+
343+
action1 = (arg: boolean) => {
344+
if (arg) {
345+
this.$repeatedAction()
346+
}
347+
this.face = '🥸'
348+
}
349+
350+
action2 = (arg: boolean) => {
351+
if (!arg) {
352+
this.$repeatedAction()
353+
}
354+
this.face = '🫤'
355+
}
356+
}
357+
358+
export const useStore = createReactStore(new Store())
359+
```
360+
324361
## Comparison
325362

326363
2n8 feels like a blend between two excellent state management libraries:

src/2n8.test.tsx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,24 @@ test('should not fire subscription until end of action', () => {
627627
expect(subscribeSpy).toHaveBeenCalledTimes(2)
628628
})
629629

630+
test('should not fire subscription if action begins with $ but state still updates', () => {
631+
class Store extends TwoAndEight {
632+
count = 999
633+
634+
$increment = () => {
635+
this.count++
636+
}
637+
}
638+
639+
const { get, subscribe } = createStore(new Store())
640+
const subscribeSpy = vi.fn<() => void>()
641+
subscribe(subscribeSpy)
642+
get('$increment')()
643+
644+
expect(get('count')).toBe(1000)
645+
expect(subscribeSpy).not.toHaveBeenCalled()
646+
})
647+
630648
test("should fail types when store hasn't extended super class", () => {
631649
class Store {
632650
count = 0

0 commit comments

Comments
 (0)