The Pglite API is asynchronous. This means that we need to manage loading states and possible errors.
xstate
allows to extract the state logic from the UI and implement it all inside state machine actors.
We can focus on handling each state and transition, without worrying about the UI. This makes it easier to extract reusable logic by combining actors.
The UI is only responsible for rendering the UI and sending events to the state machine.
This simplifies the architecture by separating UI concerns from state. It means that we can focus on the business logic and the state machine implementation in isolation, and only later compose the UI.
If you want to learn more about
xstate
, actors, and state machines, you can check out XState: Complete Getting Started Guide.
Actors and state machines
All the logic is defined inside state machines. The project contains a machines
folder where each file implements a state machine.
The UI then integrates the machines with the useMachine
hook from @xstate/react
:
pnpm add xstate @xstate/react
The project uses the latest version v5 of
xstate
.
import { useMachine } from "@xstate/react";
// ...
export default function ManageServing({
children,
log,
}: {
log: ServingSelectWithFoods;
children: React.ReactNode;
}) {
const [snapshot, send] = useMachine(machine, {
input: { quantity: log.quantity },
});
// ...
}
In the next lessons we are going to explore how to create and combine actors to implement the state machines in the project.