Skip to content
OrbContext
19 pages

Guide

React

Build a chat component against your own backend, or drop in the widget.

A React app (Vite, Create React App, Remix or any SPA) runs in the browser, so it must not hold your secret key. The pattern is: React talks to your backend, and your backend talks to OrbContext. This guide gives you a reusable hook and a small component for that.

The backend contract

The hook expects one endpoint, POST /api/chat, that accepts { message, conversationId? } and responds with newline-delimited JSON events (started, token, done, error). Each backend guide implements exactly that, so they are interchangeable.

A reusable hook

useOrbChat.ts
import { useCallback, useRef, useState } from 'react';

export interface Turn {
  id: number;
  role: 'user' | 'assistant';
  text: string;
  refused?: boolean;
}

export function useOrbChat(endpoint = '/api/chat') {
  const [turns, setTurns] = useState<Turn[]>([]);
  const [pending, setPending] = useState(false);
  const conversationId = useRef<string | undefined>(undefined);
  const controller = useRef<AbortController | null>(null);
  const nextId = useRef(0);

  const send = useCallback(
    async (message: string) => {
      const userId = nextId.current;
      const assistantId = userId + 1;
      nextId.current += 2;
      setPending(true);
      setTurns((t) => [
        ...t,
        { id: userId, role: 'user', text: message },
        { id: assistantId, role: 'assistant', text: '' },
      ]);
      const update = (fn: (turn: Turn) => Turn) =>
        setTurns((t) => t.map((turn) => (turn.id === assistantId ? fn(turn) : turn)));

      controller.current = new AbortController();
      try {
        const res = await fetch(endpoint, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ message, conversationId: conversationId.current }),
          signal: controller.current.signal,
        });
        if (!res.ok || !res.body) throw new Error(String(res.status));

        const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
        let buffer = '';
        for (;;) {
          const { value, done } = await reader.read();
          if (done) break;
          buffer += value;
          const lines = buffer.split('\n');
          buffer = lines.pop() ?? '';
          for (const line of lines.filter(Boolean)) {
            const event = JSON.parse(line);
            if (event.type === 'started') conversationId.current = event.conversationId;
            else if (event.type === 'token') update((t) => ({ ...t, text: t.text + event.value }));
            else if (event.type === 'done') update((t) => ({ ...t, refused: event.refused }));
            else if (event.type === 'error') update((t) => ({ ...t, text: event.message }));
          }
        }
      } catch (err) {
        if ((err as Error).name !== 'AbortError')
          update((t) => ({ ...t, text: 'Something went wrong. Please try again.' }));
      } finally {
        setPending(false);
      }
    },
    [endpoint],
  );

  const stop = useCallback(() => controller.current?.abort(), []);
  const reset = useCallback(() => {
    controller.current?.abort();
    conversationId.current = undefined;
    setTurns([]);
  }, []);

  return { turns, pending, send, stop, reset };
}

A component that uses it

Chat.tsx
import { useState } from 'react';
import { useOrbChat } from './useOrbChat';

export function Chat() {
  const { turns, pending, send, stop } = useOrbChat();
  const [draft, setDraft] = useState('');

  return (
    <section aria-label="Ask a question">
      <ul aria-live="polite">
        {turns.map((turn) => (
          <li key={turn.id} data-role={turn.role}>
            {turn.text || (pending ? '…' : '')}
            {turn.refused && <small> I could not find this in the documents.</small>}
          </li>
        ))}
      </ul>

      <form
        onSubmit={(e) => {
          e.preventDefault();
          if (!draft.trim() || pending) return;
          send(draft.trim());
          setDraft('');
        }}
      >
        <input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Ask a question" />
        {pending ? (
          <button type="button" onClick={stop}>Stop</button>
        ) : (
          <button type="submit">Send</button>
        )}
      </form>
    </section>
  );
}

Or skip the backend: the widget

If you only need a chat bubble, load the widget from a React app by adding its script once, for example in index.html. It uses a domain-locked public key, so nothing secret ships to the browser.

index.html
<script
  src="https://<your-api-host>/widget.js"
  data-key="pk_live_..."
  async
></script>