Skip to content

Latest commit

 

History

History
50 lines (43 loc) · 1.51 KB

use-an-xstate-machine-with-react.md

File metadata and controls

50 lines (43 loc) · 1.51 KB

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. For instance, I can grab the Confirmation Dialog machine and paste it into confirmMachine.js. Then I can grab @xstate/react which comes with a useMachine hook.

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 (
    <div className="App">
      <Dialog
        message="Are you sure you want to delete something?"
        handleConfirm={confirm}
        handleClose={close}
        showDialog={showDialog}
        errorMessage={current.context.errorMessage}
      />
      {/* other stuff */}
    </div>
  )
}

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.