Skip to content

Commit 3e28983

Browse files
committed
Add Inline Actions vs Actions In Machine Options as an XState til
1 parent 4ba4de1 commit 3e28983

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1136 TILs and counting..._
13+
_1137 TILs and counting..._
1414

1515
---
1616

@@ -1332,6 +1332,7 @@ _1136 TILs and counting..._
13321332
### XState
13331333

13341334
- [Define Event That Does Internal Self Transition](xstate/define-event-that-does-internal-self-transition.md)
1335+
- [Inline Actions vs Actions In Machine Options](xstate/inline-actions-vs-actions-in-machine-options.md)
13351336
- [Use An XState Machine With React](xstate/use-an-xstate-machine-with-react.md)
13361337

13371338
### YAML
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Inline Actions vs Actions In Machine Options
2+
3+
When first spec'ing out a machine, I find it easiest to add my on-transition
4+
actions directly inline.
5+
6+
```javascript
7+
const countingMachine = createMachine({
8+
initial: "counting",
9+
context: { count: 0 },
10+
states: {
11+
counting: {
12+
on: {
13+
INCREMENT: {
14+
actions: assign({
15+
count: (context) => context.count + 1,
16+
}),
17+
},
18+
},
19+
},
20+
},
21+
});
22+
```
23+
24+
This is not what the XState docs recommend once you move beyond prototyping
25+
your machine.
26+
27+
> It is not recommended to keep the machine config like this in production
28+
> code, as this makes it difficult to debug, serialize, test, and accurately
29+
> visualize actions.
30+
31+
When you're ready, you can refactor this by referencing the action by name and
32+
then moving the action declaration to the `actions` object of the machine
33+
options (second argument to `createMachine`).
34+
35+
```javascript
36+
const countingMachine = createMachine({
37+
initial: "counting",
38+
context: { count: 0 },
39+
states: {
40+
counting: {
41+
on: {
42+
INCREMENT: {
43+
actions: 'incrementCount',
44+
},
45+
},
46+
},
47+
},
48+
},
49+
{
50+
actions: {
51+
incrementCount: assign({
52+
count: (context) => context.count + 1,
53+
}),
54+
},
55+
});
56+
```
57+
58+
When the machine interpreter sees `'incrementCount'`, it knows to look for an
59+
action by that name in the machine options.
60+
61+
[source](https://xstate.js.org/docs/guides/actions.html)

0 commit comments

Comments
 (0)