A complete example

One React component, start to finish, with nothing left out.

Everything from the rest of this section in one file: Harbor & Pine’s chat panel. Unstyled on purpose — the point is that the Tigerbase-specific part is small and the rest is a textarea, a list and a button.

How it fits together

Mount loads the settings once. Every send is one turn, patched into the last bubble as it streams.

The files

The client

lib/tigerbase.ts
import { Tigerbase } from "@tigerbase/client";

export const tigerbase = new Tigerbase({
  key: process.env.NEXT_PUBLIC_TIGERBASE_KEY!,
});

The component

components/Chat.tsx
"use client";

import { useEffect, useRef, useState } from "react";
import { applyTheme, TigerbaseError, type AgentConfig } from "@tigerbase/client";
import { tigerbase } from "@/lib/tigerbase";

type Message = {
  role: "visitor" | "agent" | "human" | "system";
  text: string;
  id?: string;
};

/** Codes, not sentences — your copy, your language. */
function sentenceFor(err: unknown): string | null {
  if (!(err instanceof TigerbaseError)) return "Something went wrong.";
  switch (err.code) {
    case "aborted":
      return null;
    case "rate_limited":
      return `One moment — try again in ${err.retryAfterSeconds}s`;
    case "too_many_conversations":
    case "busy":
      return "We are busy right now. Try again shortly.";
    case "network":
      return "You seem to be offline.";
    case "monthly_limit":
    case "invalid_key":
    case "agent_inactive":
    case "unavailable":
    case "forbidden_origin":
      return "The assistant is not available right now.";
    default:
      return "Something went wrong.";
  }
}

export function Chat() {
  const [agent, setAgent] = useState<AgentConfig | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const [theyAreTyping, setTheyAreTyping] = useState(false);

  // One conversation for the life of the component. In a ref, not state:
  // it holds a socket, and no render depends on its identity.
  const chat = useRef(tigerbase.conversation()).current;
  const abort = useRef<AbortController | null>(null);

  useEffect(() => {
    tigerbase.config().then(setAgent);
    // Paint the account's colours. Their brand, not yours.
    tigerbase.theme().then((theme) => applyTheme(theme));

    // Every listener returns its own unsubscribe. (These open the handoff
    // socket, so socket.io-client must be installed.)
    const offs = [
      chat.on("human", ({ name }) =>
        setMessages((m) => [...m, { role: "system", text: `${name} joined` }]),
      ),
      chat.on("message", (m) =>
        setMessages((prev) => [...prev, { role: "human", text: m.content }]),
      ),
      chat.on("resolved", () =>
        setMessages((m) => [
          ...m,
          { role: "system", text: "Back to the assistant" },
        ]),
      ),
      chat.on("typing", ({ who, active }) => {
        if (who === "human") setTheyAreTyping(active);
      }),
      // Live updates could not start — usually socket.io-client is missing.
      chat.on("error", (err) => console.warn("Live handoff is off:", err.message)),
    ];

    return () => {
      offs.forEach((off) => off());
      chat.end();
    };
  }, [chat]);

  async function send(question: string) {
    const q = question.trim();
    if (!q || busy) return;

    setInput("");
    setBusy(true);
    chat.typing.stop();
    setMessages((m) => [
      ...m,
      { role: "visitor", text: q },
      { role: "agent", text: "" },
    ]);

    // Cancel a turn still arriving when a new question is sent, or the two
    // answers interleave into one bubble.
    abort.current?.abort();
    abort.current = new AbortController();

    // Updates the last message in place — the agent bubble added above.
    const patch = (fields: Partial<Message>) =>
      setMessages((m) =>
        m.map((msg, i) => (i === m.length - 1 ? { ...msg, ...fields } : msg)),
      );

    let answer = "";

    try {
      for await (const ev of chat.ask(q, { signal: abort.current.signal })) {
        if (ev.messageId) patch({ id: ev.messageId });
        if (ev.text) {
          answer += ev.text;
          patch({ text: answer });
        }
        // A person has the conversation: they will answer, not the agent.
        if (ev.handoff && !answer) {
          patch({ role: "system", text: "Passed to the team." });
        }
      }
    } catch (err) {
      const sentence = sentenceFor(err);
      if (sentence) patch({ role: "system", text: sentence });
    } finally {
      setBusy(false);
    }
  }

  if (!agent) return null;

  return (
    <div dir={agent.language === "ar" ? "rtl" : "ltr"}>
      <header>
        <h2>{agent.botName ?? "Harbor & Pine"}</h2>
        {agent.tagline && <p>{agent.tagline}</p>}
      </header>

      {/* The welcome and suggestions the account wrote, not ones you invented */}
      {messages.length === 0 && (
        <div>
          <p>{agent.initialMessage ?? agent.welcomeMessage}</p>
          {agent.starterQuestions.map((q) => (
            <button key={q} onClick={() => send(q)}>
              {q}
            </button>
          ))}
        </div>
      )}

      <ul>
        {messages.map((m, i) => (
          <li key={i} data-role={m.role}>
            {m.text}

            {/* Only an answer the server gave an id to can be rated */}
            {m.role === "agent" && m.id && (
              <span>
                <button onClick={() => chat.rate(m.id!, "up")}>👍</button>
                <button onClick={() => chat.rate(m.id!, "down")}>👎</button>
              </span>
            )}
          </li>
        ))}
      </ul>

      {theyAreTyping && <p>Typing…</p>}

      <textarea
        value={input}
        disabled={busy}
        onChange={(e) => {
          setInput(e.target.value);
          // No-op while nobody has taken over, so this is free.
          e.target.value ? chat.typing.keystroke() : chat.typing.stop();
        }}
        onKeyDown={(e) => {
          if (e.key === "Enter" && !e.shiftKey) {
            e.preventDefault();
            send(input);
          }
        }}
      />

      <button onClick={() => send(input)} disabled={busy || !input.trim()}>
        Send
      </button>

      {agent.handoffEnabled && (
        <button
          onClick={() => chat.requestHuman({ reason: "Asked for a person" })}
        >
          Talk to a person
        </button>
      )}

      <button
        onClick={() => {
          chat.reset();
          setMessages([]);
        }}
      >
        Start over
      </button>
    </div>
  );
}

WarningThe on() listeners need socket.io-client

They open the handoff socket, and the socket library is an optional peer. Without it the four live events never come and the error listener is told why — everything else in the component still works. Install it, or poll as shown on Handing to a person.

What to notice

The patch helper

Streaming means updating the last message many times a second. Patching only the last entry keeps every other message object the same, so a long conversation does not re-render every bubble on every word.

The abort ref

Without it, a visitor who types while an answer is arriving gets two answers in one bubble — and it looks like the agent lost its mind rather than like a missing cancel. aborted is then swallowed by sentenceFor, because you asked for it.

The unsubscribe array

Every on() returns its own; dropping one leaks a listener per mount, which in a modal that opens and closes is a real leak. end() after them closes the socket and stops the typing signal.

The empty bubble on handoff

When a person has the conversation, a turn comes back with handoff and no text. Replacing the empty agent bubble with a line of status is what keeps the thread from showing a blank answer.

NoteThere is no useAgent() hook — yet

A hook is forty lines over this, and it would be an opinion about state shape baked into a package that otherwise has none. If enough people write the same forty lines it belongs in the package, under a /react subpath rather than as a second package.

Copying this file is the supported answer until then. Building for phones? The same calls work in React Native; the next page covers the one thing that needs you there.