Skip to content

Commit acc4d2a

Browse files
committed
actors.mdx: provide a custom actor logic example
1 parent f724032 commit acc4d2a

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

docs/actors.mdx

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,50 @@ const loggingToggleLogic = withLogging(toggleLogic);
464464

465465
## Custom actor logic
466466

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

469512
## Empty actors
470513

0 commit comments

Comments
 (0)