Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Persist callback input #4307

Merged
merged 3 commits into from
Sep 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>(
_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', () => {
davidkpiano marked this conversation as resolved.
Show resolved Hide resolved
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