diff --git a/README.md b/README.md index b982b98..9f62f08 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). -_1120 TILs and counting..._ +_1121 TILs and counting..._ --- @@ -1315,6 +1315,10 @@ _1120 TILs and counting..._ - [Update asdf Plugins With Latest Package Versions](workflow/update-asdf-plugins-with-latest-package-versions.md) - [View The PR For The Current GitHub Branch](workflow/view-the-pr-for-the-current-github-branch.md) +### XState + +- [Use An XState Machine With React](xstate/use-an-xstate-machine-with-react.md) + ### YAML - [Create Multi-Line Strings Without The Line Breaks](yaml/create-multi-line-strings-without-the-line-breaks.md) diff --git a/xstate/use-an-xstate-machine-with-react.md b/xstate/use-an-xstate-machine-with-react.md new file mode 100644 index 0000000..207d412 --- /dev/null +++ b/xstate/use-an-xstate-machine-with-react.md @@ -0,0 +1,50 @@ +# Use An XState Machine With React + +There are a bunch of well-constructed XState machines available to directly +copy into your project from [XState Catalogue](https://xstate-catalogue.com/). +For instance, I can grab the [Confirmation Dialog +machine](https://xstate-catalogue.com/machines/confirmation-dialog) and paste +it into `confirmMachine.js`. Then I can grab +[`@xstate/react`](https://xstate.js.org/docs/packages/xstate-react/) which +comes with a `useMachine` hook. + +```javascript +import * as React from "react"; +import { useMachine } from "@xstate/react"; +import confirmMachine from "./confirmMachine"; +import Dialog from "./dialog"; + +export default function App() { + const [current, send] = useMachine(confirmMachine); + + const deleteAction = () => { /* ... */ }; + + const showDialog = current.value !== "closed"; + const open = () => { + send({ type: "OPEN_DIALOG", action: deleteAction }); + }; + const close = () => { + send("CANCEL"); + }; + const confirm = () => { + send("CONFIRM"); + }; + + return ( +
+ + {/* other stuff */} +
+ ) +} +``` + +The `useMachine` call both interprets and starts up the machine service. The +`current` value is everything about the _current_ state of the machine. The +`send` is a function for dispatching transitions between machine states.