Skip to content

Commit

Permalink
fix: onContextChange for updates
Browse files Browse the repository at this point in the history
  • Loading branch information
tdreyno committed Apr 18, 2022
1 parent f1e8d42 commit 2605208
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 17 deletions.
2 changes: 1 addition & 1 deletion src/__tests__/boundActions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,6 @@ describe("Bound actions", () => {
])

expect(runtime.currentState().data).toBe(36)
expect(onChange).toHaveBeenCalledTimes(5)
expect(onChange).toHaveBeenCalledTimes(10)
})
})
30 changes: 20 additions & 10 deletions src/__tests__/onContextChange.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { ActionCreatorType, Enter, createAction, enter } from "../action"
import { Context, createInitialContext } from "../context"

import { createInitialContext } from "../context"
import { createRuntime } from "../runtime"
import { noop } from "../effect"
import { state } from "../state"
Expand All @@ -27,28 +28,37 @@ describe("onContextChange", () => {
expect(onChange).toHaveBeenCalledTimes(1)
})

test("should run callback once on update", async () => {
test("should run callback on update", async () => {
const trigger = createAction("Trigger")
type Trigger = ActionCreatorType<typeof trigger>

const A = state<Enter | Trigger, string>(
const A = state<Enter | Trigger, number>(
{
Enter: noop,
Trigger: (name, _, { update }) => update(name + name),
Enter: (n, _, { update }) => [update(n + 1), trigger()],
Trigger: async (n, _, { update }) => update(n + 1),
},
{ name: "A" },
)

const context = createInitialContext([A("Test")])
const context = createInitialContext([A(1)])

const runtime = createRuntime(context, ["Trigger"])

const onChange = jest.fn()
let i = 0
const onChange = jest.fn((context: Context) => {
const { data } = context.currentState

runtime.onContextChange(onChange)
if (i++ == 0) {
expect(data).toBe(2)
} else {
expect(data).toBe(3)
}
})

await runtime.run(trigger())
expect.assertions(3)

expect(onChange).toHaveBeenCalledTimes(1)
runtime.onContextChange(onChange)

await runtime.run(enter())
})
})
7 changes: 1 addition & 6 deletions src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ export class Runtime {
effect("nextState", targetState, () => {
this.context.history.pop()
this.context.history.push(targetState)
this.#contextDidChange()
}),

// Add a log effect.
Expand All @@ -249,12 +250,6 @@ export class Runtime {

// Run enter on next state
enter(),

// Notify listeners of change
// effect("contextChange", undefined, () => {
// // Only state changes (and updates) can change context
// this.onContextChange_()
// }),
]

// Run exit on prior state first
Expand Down

0 comments on commit 2605208

Please sign in to comment.