@ai-digital-factory/state-flow-react
v0.2.0
Published
React bindings for State Flow client instances: provider, instance and selector hooks, <Match>.
Readme
@ai-digital-factory/state-flow-react
React bindings for State Flow client instances (ADR 0097, 0099): a provider, the instance hook and the snapshot selector hook. Separate from the authoring Library.
import {
StateFlowProvider,
useInstance,
useSnapshot,
} from "@ai-digital-factory/state-flow-react";
function LoanForm({ flow }: { flow: LoanRequestFlow }) {
const loaded = useInstance(flow, "loan-form:A-17");
if (loaded.status === "loading") return <Spinner />;
if (loaded.status === "failed") return <Problem error={loaded.error} />;
return <Step form={loaded.instance} />;
}
function Step({ form }: { form: LoanRequestForm }) {
const state = useSnapshot(form, (snapshot) => snapshot.state);
const submitting = useSnapshot(
form,
(snapshot) => snapshot.status.kind === "running",
);
if (state === "amount") {
return (
<AmountStep
busy={submitting}
onSubmit={(amount) =>
form
.when("amount")
.transition("submit-request")
.payload({ amount })
.run(() => undefined)
}
/>
);
}
// …
}StateFlowProvider/useClientHost: the application's one client host.useInstance(flow, instanceId, input?): ensures (creates, or returns the page's) instance once per identity and returns the typed instance, or the loading or failed state. A Flow with aninputSchemarequiresinput, recorded when the instance is created (ADR 0102).useSnapshot(instance, selector, isEqual): re-renders only when the selected value changes; keeps the instance's and selector's types.- Dispatch uses the instance's own builder:
instance.when(state).transition(name).payload(value).run(handlers)(ADR 0107).
