Skip to content

Commit 0511949

Browse files
authored
Merge pull request #252 from audionerd/docs-custom-actor-logic
actors.mdx: Custom actor logic section
2 parents 31792cd + acc4d2a commit 0511949

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

docs/actors.mdx

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ In the actor model, actors are objects that can communicate with each other. The
3737

3838
Actor logic is the actor’s logical “model” (brain, blueprint, DNA, etc.) It describes how the actor should change behavior when receiving an event. You can create actor logic using **[actor logic creators](#actor-logic-creators)**.
3939

40-
In XState, actor logic is defined by an object containing methods like `.transition(...)`, `.getInitialState()`, `.getSnapshot()`, and more. This object tells an interpreter how to update an actor’s internal state when it receives an event and which effects to execute (if any).
40+
In XState, actor logic is defined by an object implementing the `ActorLogic` interface, containing methods like `.transition(...)`, `.getInitialState()`, `.getPersistedState()`, and more. This object tells an interpreter how to update an actor’s internal state when it receives an event and which effects to execute (if any).
4141

4242
## Creating actors
4343

@@ -464,9 +464,52 @@ function withLogging(actorLogic) {
464464
const loggingToggleLogic = withLogging(toggleLogic);
465465
```
466466

467-
## Custom actors
467+
## Custom actor logic
468468

469-
_Coming soon_
469+
Custom actor logic can be defined with an object that implements the `ActorLogic` interface.
470+
471+
For example, here’s a custom actor logic object with a `transition` function that operates as a simple reducer:
472+
473+
```ts
474+
import { createActor, EventObject, ActorLogic, Snapshot } from "xstate";
475+
476+
const countLogic: ActorLogic<
477+
Snapshot<undefined> & { context: number },
478+
EventObject
479+
> = {
480+
transition: (state, event) => {
481+
if (event.type === 'INC') {
482+
return {
483+
...state,
484+
context: state.context + 1
485+
};
486+
} else if (event.type === 'DEC') {
487+
return {
488+
...state,
489+
context: state.context - 1
490+
};
491+
}
492+
return state;
493+
},
494+
getInitialState: () => ({
495+
status: 'active',
496+
output: undefined,
497+
error: undefined,
498+
context: 0
499+
}),
500+
getPersistedState: (s) => s
501+
};
502+
503+
const actor = createActor(countLogic)
504+
actor.subscribe(state => {
505+
console.log(state.context)
506+
})
507+
actor.start() // => 0
508+
actor.send({ type: 'INC' }) // => 1
509+
actor.send({ type: 'INC' }) // => 2
510+
```
511+
512+
For further examples, see implementations of `ActorLogic` in the source code, like the `fromTransition` actor logic creator, or the examples in the tests.
470513

471514
## Empty actors
472515

0 commit comments

Comments
 (0)