Skip to content

Commit

Permalink
Fixed an issue with actors deep in the tree failing to rehydrate (#4491)
Browse files Browse the repository at this point in the history
  • Loading branch information
Andarist committed Nov 23, 2023
1 parent 1008cee commit c0025c3
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/deep-actor-rehydration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'xstate': patch
---

Fixed an issue with actors deep in the tree failing to rehydrate.
4 changes: 1 addition & 3 deletions packages/core/src/StateMachine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,13 +560,11 @@ export class StateMachine<
return;
}

const actorState = logic.restoreState?.(childState, _actorScope);

const actorRef = createActor(logic, {
id: actorId,
parent: _actorScope?.self,
syncSnapshot: actorData.syncSnapshot,
state: actorState,
state: childState,
src,
systemId: actorData.systemId
});
Expand Down
72 changes: 71 additions & 1 deletion packages/core/test/rehydration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import {
createMachine,
createActor,
fromPromise,
fromObservable
fromObservable,
assign,
sendTo
} from '../src/index.ts';

describe('rehydration', () => {
Expand Down Expand Up @@ -364,4 +366,72 @@ describe('rehydration', () => {

expect(spy.mock.calls).toEqual([[42], [100]]);
});

it('should be able to rehydrate an actor deep in the tree', () => {
const grandchild = createMachine({
context: {
count: 0
},
on: {
INC: {
actions: assign({
count: ({ context }) => context.count + 1
})
}
}
});
const child = createMachine(
{
invoke: {
src: 'grandchild',
id: 'grandchild'
},
on: {
INC: {
actions: sendTo('grandchild', {
type: 'INC'
})
}
}
},
{
actors: {
grandchild
}
}
);
const machine = createMachine(
{
invoke: {
src: 'child',
id: 'child'
},
on: {
INC: {
actions: sendTo('child', {
type: 'INC'
})
}
}
},
{
actors: {
child
}
}
);

const actorRef = createActor(machine).start();
actorRef.send({ type: 'INC' });

const persistedState = actorRef.getPersistedState();
const actorRef2 = createActor(machine, { state: persistedState });

expect(
actorRef2
.getSnapshot()
.children.child.getSnapshot()
.children.grandchild.getSnapshot().context.count
).toBe(1);
});
});

0 comments on commit c0025c3

Please sign in to comment.