diff --git a/README.md b/README.md index ff1a8b1..94c8628 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1144 TILs and counting..._ +_1145 TILs and counting..._ --- @@ -1336,6 +1336,7 @@ _1144 TILs and counting..._ ### XState +- [Always Use Inline Functions With Assign](xstate/always-use-inline-functions-with-assign.md) - [Define Event That Does Internal Self Transition](xstate/define-event-that-does-internal-self-transition.md) - [Events Stop Propagating Once Handled](xstate/events-stop-propagating-once-handled.md) - [Inline Actions vs Actions In Machine Options](xstate/inline-actions-vs-actions-in-machine-options.md) diff --git a/xstate/always-use-inline-functions-with-assign.md b/xstate/always-use-inline-functions-with-assign.md new file mode 100644 index 0000000..a1d6ab9 --- /dev/null +++ b/xstate/always-use-inline-functions-with-assign.md @@ -0,0 +1,50 @@ +# Always Use Inline Functions With Assign + +The [`assign` +action](https://xstate.js.org/docs/guides/context.html#assign-action) allows +you to update the context of the state machine. There are a couple ways to use +`assign`, but you should prefer the inline function style. + +Technically `assign` can be passed an object literal like so to set a static +value: + +```javascript +{ + actions: { + resetCount: assign({ + count: 0 + }) + } +} +``` + +However, this causes confusion for the TypeScript compiler and can create +surprising and unrelated type errors in the parts the code that use the +machine. + +To keep the compiler happy, you should instead use inline functions. Either +like this: + +```javascript +{ + actions: { + resetCount: assign((_context) => { + return { + count: 0 + } + }) + } +} +``` + +or like this: + +```javascript +{ + actions: { + resetCount: assign({ + count: (_context) => 0 + }) + } +} +```