Skip to content

Commit

Permalink
Persist callback input (#4307)
Browse files Browse the repository at this point in the history
* Persist callback input

* tweak test case

---------

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
  • Loading branch information
davidkpiano and Andarist committed Sep 26, 2023
1 parent 6ec18f1 commit 0c7b3aa
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/wise-eggs-train.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'xstate': patch
---

The `input` of a callback actor created with `fromCallback(...)` will now be properly restored when the actor is persisted.
7 changes: 6 additions & 1 deletion packages/core/src/actors/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ export function fromCallback<TEvent extends EventObject, TInput = unknown>(
_dispose: undefined
};
},
getPersistedState: ({ _dispose, _receivers, ...rest }) => rest
getPersistedState: ({ _dispose, _receivers, ...rest }) => rest,
restoreState: (state) => ({
_receivers: new Set(),
_dispose: undefined,
...state
})
};
}
50 changes: 50 additions & 0 deletions packages/core/test/actorLogic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,56 @@ describe('callback logic (fromCallback)', () => {

createActor(machine).start();
});

it('should persist the input of a callback', () => {
const spy = jest.fn();
const machine = createMachine(
{
types: {} as { events: { type: 'EV'; data: number } },
initial: 'a',
states: {
a: {
on: {
EV: 'b'
}
},
b: {
invoke: {
src: 'cb',
input: ({ event }) => event.data
}
}
}
},
{
actors: {
cb: fromCallback(({ input }) => {
spy(input);
})
}
}
);

const actor = createActor(machine);
actor.start();
actor.send({
type: 'EV',
data: 13
});

const state = actor.getPersistedState();

actor.stop();

spy.mockClear();

const restoredActor = createActor(machine, { state });

restoredActor.start();

expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(13);
});
});

describe('machine logic', () => {
Expand Down

0 comments on commit 0c7b3aa

Please sign in to comment.