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

Pass self to context factories #4616

Merged
merged 1 commit into from
Dec 22, 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
17 changes: 17 additions & 0 deletions .changeset/red-terms-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'xstate': minor
---

`context` factories receive `self` now so you can immediately pass that as part of the input to spawned actors.

```ts
setup({
/* ... */
}).createMachine({
context: ({ spawn, self }) => {
return {
childRef: spawn('child', { input: { parent: self } })
};
}
});
```
4 changes: 2 additions & 2 deletions packages/core/src/StateMachine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,8 +372,8 @@ export class StateMachine<
);

if (typeof context === 'function') {
const assignment = ({ spawn, event }: any) =>
context({ spawn, input: event.input });
const assignment = ({ spawn, event, self }: any) =>
context({ spawn, input: event.input, self });
return resolveActionsAndContext(
preInitial,
initEvent,
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,11 @@ export class Actor<TLogic extends AnyActorLogic>
* @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
*/
public getSnapshot(): SnapshotFrom<TLogic> {
if (isDevelopment && !this._snapshot) {
throw new Error(
`Snapshot can't be read while the actor initializes itself`
Copy link
Member

@davidkpiano davidkpiano Dec 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`Snapshot can't be read while the actor initializes itself`
`Snapshot cannot be read before actor is being initialized.`

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggested change is not correct. This is perfectly valid:

const actorRef = createActor(machine)
actorRef.getSnapshot()
actorRef.start()

This isn't:

const machine = createMachine({
  context: ({ self }) => {
    self.getSnapshot() // we can't do this
    return {}
  }
})
createActor(machine)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh okay, makes sense

);
}
return this._snapshot;
}
}
Expand Down
32 changes: 26 additions & 6 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1302,14 +1302,34 @@ export type MachineImplementations<
type InitialContext<
TContext extends MachineContext,
TActor extends ProvidedActor,
TInput
> = TContext | ContextFactory<TContext, TActor, TInput>;
TInput,
TEvent extends EventObject
> = TContext | ContextFactory<TContext, TActor, TInput, TEvent>;

export type ContextFactory<
TContext extends MachineContext,
TActor extends ProvidedActor,
TInput
> = ({ spawn, input }: { spawn: Spawner<TActor>; input: TInput }) => TContext;
TInput,
TEvent extends EventObject = EventObject
> = ({
spawn,
input,
self
}: {
spawn: Spawner<TActor>;
input: TInput;
self: ActorRef<
MachineSnapshot<
TContext,
TEvent,
Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`
StateValue,
string,
unknown
>,
TEvent
>;
}) => TContext;

export type MachineConfig<
TContext extends MachineContext,
Expand Down Expand Up @@ -1358,8 +1378,8 @@ export type MachineConfig<
output?: Mapper<TContext, DoneStateEvent, TOutput, TEvent> | TOutput;
}) &
(MachineContext extends TContext
? { context?: InitialContext<LowInfer<TContext>, TActor, TInput> }
: { context: InitialContext<LowInfer<TContext>, TActor, TInput> });
? { context?: InitialContext<LowInfer<TContext>, TActor, TInput, TEvent> }
: { context: InitialContext<LowInfer<TContext>, TActor, TInput, TEvent> });

export interface ProvidedActor {
src: string;
Expand Down
36 changes: 36 additions & 0 deletions packages/core/test/actor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1691,4 +1691,40 @@ describe('actors', () => {

expect(actual).toEqual(['stop 1', 'start 2']);
});

it('should be possible to pass `self` as input to a child machine from within the context factory', () => {
const spy = jest.fn();

const child = createMachine({
types: {} as {
context: {
parent: AnyActorRef;
};
input: {
parent: AnyActorRef;
};
},
context: ({ input }) => ({
parent: input.parent
}),
entry: sendTo(({ context }) => context.parent, { type: 'GREET' })
});

const machine = createMachine({
context: ({ spawn, self }) => {
return {
childRef: spawn(child, { input: { parent: self } })
};
},
on: {
GREET: {
actions: spy
}
}
});

createActor(machine).start();

expect(spy).toHaveBeenCalledTimes(1);
});
});
File renamed without changes.