Skip to content

Commit 84aba3e

Browse files
committed
Add Always Use Inline Functions With Assign as an xstate til
1 parent 45fde23 commit 84aba3e

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-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-
_1144 TILs and counting..._
13+
_1145 TILs and counting..._
1414

1515
---
1616

@@ -1336,6 +1336,7 @@ _1144 TILs and counting..._
13361336

13371337
### XState
13381338

1339+
- [Always Use Inline Functions With Assign](xstate/always-use-inline-functions-with-assign.md)
13391340
- [Define Event That Does Internal Self Transition](xstate/define-event-that-does-internal-self-transition.md)
13401341
- [Events Stop Propagating Once Handled](xstate/events-stop-propagating-once-handled.md)
13411342
- [Inline Actions vs Actions In Machine Options](xstate/inline-actions-vs-actions-in-machine-options.md)
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Always Use Inline Functions With Assign
2+
3+
The [`assign`
4+
action](https://xstate.js.org/docs/guides/context.html#assign-action) allows
5+
you to update the context of the state machine. There are a couple ways to use
6+
`assign`, but you should prefer the inline function style.
7+
8+
Technically `assign` can be passed an object literal like so to set a static
9+
value:
10+
11+
```javascript
12+
{
13+
actions: {
14+
resetCount: assign({
15+
count: 0
16+
})
17+
}
18+
}
19+
```
20+
21+
However, this causes confusion for the TypeScript compiler and can create
22+
surprising and unrelated type errors in the parts the code that use the
23+
machine.
24+
25+
To keep the compiler happy, you should instead use inline functions. Either
26+
like this:
27+
28+
```javascript
29+
{
30+
actions: {
31+
resetCount: assign((_context) => {
32+
return {
33+
count: 0
34+
}
35+
})
36+
}
37+
}
38+
```
39+
40+
or like this:
41+
42+
```javascript
43+
{
44+
actions: {
45+
resetCount: assign({
46+
count: (_context) => 0
47+
})
48+
}
49+
}
50+
```

0 commit comments

Comments
 (0)