# Examples

> Try local examples for reactive state, data-query recovery, custom components, and parser diagnostics, with their source code.

Source: https://ai.honestui.com/docs/generative/examples

These examples run the local renderer and runtime. They use fixed programs and labeled sample data so you can inspect the behavior before connecting a model. Open each **Code** tab to see the React integration.

For layout, form validation, charts, tabs, and token replay, use the [main playground](/docs/generative#try-it-locally). For sending messages and switching conversations, use the [chat demo](/docs/generative/chat#try-the-chat-shell).

## Save and restore state [#save-and-restore-state]

Add to the count, save a snapshot, change it again, then restore. The emitted state map is visible below the controls. [State and forms](/docs/generative/state) explains how to store it with a response.

```tsx
"use client";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { Renderer, honestLibrary } from "@/registry/generative";

export const stateProgram = `$quantity = 1
root = Stack([TextContent("Example packing count: " + $quantity), buttons])
buttons = Buttons([Button("Add one", @Set($quantity, $quantity + 1), "primary"), Button("Reset count", @Reset($quantity), "secondary")])`;

export function GenerativeStateDemo() {
  const [state, setState] = React.useState<Record<string, unknown>>({});
  const [saved, setSaved] = React.useState<Record<string, unknown> | null>(null);
  const [initialState, setInitialState] = React.useState<Record<string, unknown>>({});
  const [version, setVersion] = React.useState(0);
  const [status, setStatus] = React.useState("Nothing saved yet.");
  return (
    <div className="grid min-w-0 gap-4 p-4" data-slot="generative-state-demo">
      <p className="m-0 text-sm text-muted-foreground">Local example. Add to the count, save it, change it, then restore.</p>
      <Renderer key={version} response={stateProgram} library={honestLibrary} initialState={initialState} onStateUpdate={setState} />
      <div className="flex flex-wrap gap-2">
        <Button variant="secondary" onClick={() => { setSaved(structuredClone(state)); setStatus("Snapshot saved in this preview."); }}>Save snapshot</Button>
        <Button variant="secondary" disabled={saved === null} onClick={() => {
          if (saved === null) return;
          setInitialState(structuredClone(saved)); setVersion(value => value + 1); setStatus("Saved snapshot restored.");
        }}>Restore snapshot</Button>
      </div>
      <p role="status" className="m-0 text-sm">{status}</p>
      <pre aria-label="Current renderer state" className="m-0 overflow-x-auto text-xs">{JSON.stringify(state, null, 2)}</pre>
    </div>
  );
}

```

## Recover a data query [#recover-a-data-query]

Load the fixture, simulate failure, then retry the query. The source program stays the same. [Data and tools](/docs/generative/tools) explains the provider and recovery hooks.

```tsx
"use client";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { Renderer, honestLibrary, useRendererQuery } from "@/registry/generative";

export const queryProgram = `sales = Query("example_sales", {}, {labels: [], values: []})
root = Stack([InlineHeader("Example orders", "Local fixture data"), chart])
chart = BarChart(sales.labels, [Series("Orders", sales.values)], "grouped")`;

function QueryFeedback({ recover }: { recover: () => void }) {
  const { isLoading, errors, retry } = useRendererQuery();
  return (
    <>
      {isLoading && <p role="status" className="m-0 text-sm">Loading local example data…</p>}
      {errors.length > 0 && <div role="alert" className="grid gap-2 text-sm">
        <p className="m-0">The example data query failed. The source program has not changed.</p>
        <Button variant="secondary" onClick={() => { recover(); retry(); }}>Retry data query</Button>
      </div>}
      <Renderer.Content />
    </>
  );
}

export function GenerativeQueryDemo() {
  const fail = React.useRef(false);
  const [version, setVersion] = React.useState(0);
  const tools = React.useMemo(() => ({
    example_sales: async () => {
      await new Promise(resolve => setTimeout(resolve, 400));
      if (fail.current) throw new Error("Deliberate example query failure");
      return { labels: ["Jan", "Feb", "Mar"], values: [12, 18, 15] };
    },
  }), []);
  return (
    <div className="grid min-w-0 gap-4 p-4" data-slot="generative-query-demo">
      <p className="m-0 text-sm text-muted-foreground">This query reads a local fixture after a short delay. No network or model request is sent.</p>
      <div className="flex flex-wrap gap-2">
        <Button variant="secondary" onClick={() => { fail.current = false; setVersion(value => value + 1); }}>Load example data</Button>
        <Button variant="secondary" onClick={() => { fail.current = true; setVersion(value => value + 1); }}>Simulate query failure</Button>
      </div>
      <Renderer key={version} response={queryProgram} library={honestLibrary} toolProvider={tools}>
        <QueryFeedback recover={() => { fail.current = false; }} />
      </Renderer>
    </div>
  );
}

```

## Register a product component [#register-a-product-component]

`DeliveryStatus` is added to the library with a schema and a React implementation using Honest UI Card and Badge. Its values are illustrative; there is no tracking service. [Component library](/docs/generative/library#extend-the-library) explains the extension contract.

```tsx
"use client";
import { z } from "zod/v4";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { defineComponent, honestLibrary, Renderer } from "@/registry/generative";

const DeliveryStatus = defineComponent({
  name: "DeliveryStatus",
  description: "A delivery summary supplied by the application",
  props: z.object({
    reference: z.string(),
    status: z.enum(["Preparing", "In transit", "Delivered"]),
    detail: z.string(),
  }),
  component: ({ props }) => (
    <Card>
      <CardHeader><CardTitle>{props.reference}</CardTitle></CardHeader>
      <CardContent className="grid gap-3">
        <Badge>{props.status}</Badge>
        <p className="m-0 text-sm">{props.detail}</p>
      </CardContent>
    </Card>
  ),
});
export const deliveryLibrary = honestLibrary.extend({ components: { add: [DeliveryStatus] } });
export const customProgram = 'root = Stack([DeliveryStatus("Example shipment 1042", "In transit", "Illustrative status. No tracking service is connected.")])';

export function GenerativeCustomDemo() {
  return <div className="grid min-w-0 gap-4 p-4" data-slot="generative-custom-demo">
    <p className="m-0 text-sm text-muted-foreground">DeliveryStatus is registered by this example. Its card and badge are Honest UI components.</p>
    <Renderer library={deliveryLibrary} response={customProgram} />
  </div>;
}

```

## Inspect and correct a program [#inspect-and-correct-a-program]

Break the component name to produce parser diagnostics, edit the source, or restore the valid program. Invalid output is kept out of the renderer in this example. This is local validation and manual correction, not model repair.

```tsx
"use client";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Renderer, honestLibrary, createParser } from "@/registry/generative";

const validSource = 'root = Stack([TextContent("This example program is valid.")])';
const parser = createParser(honestLibrary.toJSONSchema(), honestLibrary.root);
export function GenerativeDiagnosticsDemo() {
  const id = React.useId();
  const [source, setSource] = React.useState(validSource);
  const result = React.useMemo(() => parser.parse(source), [source]);
  const errors = result.meta.errors.filter(error => error.severity !== "warning");
  const valid = errors.length === 0 && result.meta.unresolved.length === 0 && !result.meta.incomplete && result.root !== null;
  return <div className="grid min-w-0 gap-4 p-4" data-slot="generative-diagnostics-demo">
    <p className="m-0 text-sm text-muted-foreground">Change a component name to see local parser diagnostics. Restoring source makes no model request.</p>
    <div className="grid gap-2">
      <Label htmlFor={id}>Program to validate</Label>
      <Textarea id={id} rows={3} value={source} onChange={event => setSource(event.target.value)} className="font-mono text-xs" />
    </div>
    <div className="flex flex-wrap gap-2">
      <Button variant="secondary" onClick={() => setSource('root = Stack([UnknownCard("Example")])')}>Break component name</Button>
      <Button variant="secondary" onClick={() => setSource(validSource)}>Restore valid source</Button>
    </div>
    {valid ? <><p role="status" className="m-0 text-sm">Program passed local validation.</p><Renderer response={source} library={honestLibrary} /></> :
      <div role="alert" className="grid gap-2 text-sm">
        <p className="m-0">The program is invalid. Correct its source before rendering.</p>
        {errors.map((error, index) => <p key={index} className="m-0"><code>{error.code}</code>: {error.message}</p>)}
        {result.meta.unresolved.length > 0 && <p className="m-0">Unresolved references: {result.meta.unresolved.join(", ")}</p>}
        {result.meta.incomplete && <p className="m-0">A statement is incomplete.</p>}
        {result.root === null && <p className="m-0">No valid root was found.</p>}
      </div>}
  </div>;
}

```

See [Language diagnostics](/docs/generative/language#read-diagnostics-before-changing-the-model) for common causes and [Server repair](/docs/generative/server#supply-your-own-repair) for connecting your own correction model.
