diff --git a/packages/core/src/actions/spawnChild.ts b/packages/core/src/actions/spawnChild.ts index b9f11990d4..41752d3918 100644 --- a/packages/core/src/actions/spawnChild.ts +++ b/packages/core/src/actions/spawnChild.ts @@ -40,13 +40,15 @@ function resolveSpawn( systemId, src, input, - syncSnapshot + syncSnapshot, + snapshot: persistedSnapshot }: { id: ResolvableActorId; systemId: string | undefined; src: AnyActorLogic | string; input?: unknown; syncSnapshot: boolean; + snapshot?: any; } ) { const logic = @@ -63,6 +65,7 @@ function resolveSpawn( src, parent: actorScope.self, syncSnapshot, + snapshot: persistedSnapshot, systemId, input: typeof input === 'function' @@ -171,6 +174,7 @@ type SpawnArguments< systemId?: string; input?: unknown; syncSnapshot?: boolean; + snapshot?: any; } ]; @@ -183,7 +187,7 @@ export function spawnChild< >( ...[ src, - { id, systemId, input, syncSnapshot = false } = {} as any + { id, systemId, input, syncSnapshot = false, snapshot } = {} as any ]: SpawnArguments ): SpawnAction { function spawnChild( @@ -201,6 +205,7 @@ export function spawnChild< spawnChild.src = src; spawnChild.input = input; spawnChild.syncSnapshot = syncSnapshot; + spawnChild.snapshot = snapshot; spawnChild.resolve = resolveSpawn; spawnChild.execute = executeSpawn; diff --git a/packages/core/src/spawn.ts b/packages/core/src/spawn.ts index 6f5621a926..82eb9e3106 100644 --- a/packages/core/src/spawn.ts +++ b/packages/core/src/spawn.ts @@ -57,6 +57,7 @@ export type Spawner = IsLiteralString< systemId?: string; input?: TLogic extends string ? unknown : InputFrom; syncSnapshot?: boolean; + snapshot?: any; } ) => TLogic extends string ? AnyActorRef : ActorRefFrom; @@ -67,7 +68,7 @@ export function createSpawner( spawnedChildren: Record ): Spawner { const spawn: Spawner = (src, options = {}) => { - const { systemId, input } = options; + const { systemId, input, snapshot } = options; if (typeof src === 'string') { const logic = resolveReferencedActor(machine, src); @@ -90,7 +91,8 @@ export function createSpawner( }) : input, src, - systemId + systemId, + snapshot }) as any; spawnedChildren[actorRef.id] = actorRef; diff --git a/packages/core/test/spawnChild.test.ts b/packages/core/test/spawnChild.test.ts index 8d54c79818..a0a6cab45c 100644 --- a/packages/core/test/spawnChild.test.ts +++ b/packages/core/test/spawnChild.test.ts @@ -5,6 +5,7 @@ import { createMachine, fromObservable, fromPromise, + fromTransition, sendTo, spawnChild } from '../src'; @@ -112,4 +113,25 @@ describe('spawnChild action', () => { expect(spy).toHaveBeenCalledTimes(1); }); + + it('can restore from a persisted snapshot', () => { + const countLogic = fromTransition((s) => s, 0); + + const actor = createActor( + createMachine({ + entry: spawnChild(countLogic, { + id: 'child', + snapshot: { + context: 100 + } + }) + }) + ); + + actor.start(); + + expect(actor.getSnapshot().children.child.getSnapshot().context).toEqual( + 100 + ); + }); });