React binding
@openmaxai/chat-store/react: ChatStoreProvider, which hands the store to components; useMessages and useMessage, which subscribe and leave fetching to the thread loader; and useChatStore.
React binding
The exports of the @openmaxai/chat-store/react entry point: the Provider that hands the store to components, and the hooks that read the store. Status, wiring in a host and the index of all exports are on the overview. The hooks on this page are the store package's implementation of the hooks application code will read the store with (the SDK is to re-export them), and today only useMessages, useMessage, useConversation and useUnread of them exist, plus useMessageByClientId, which reads one by client_msg_id, and useConversationList, which reads the conversation list.
The hooks only subscribe and do no fetching: ChatStoreProvider creates a thread loader of the root entry point from its props, the hooks subscribe to the read state it gives with useSyncExternalStore, and mounting, unmounting, paging and retrying are all handed to it. So they re-render only when the part they read changed, and fetching behaves the same as without React. They contain no UI.
chat-store-provider.tsx
import { createChatGapFillScheduler, createChatStore } from "@openmaxai/chat-store";
import { ChatStoreProvider, useMessages } from "@openmaxai/chat-store/react";
// One per host (per signed-in user).
const store = createChatStore();
const gapFill = createChatGapFillScheduler({ store, source: host.messaging });
export function ChatRoot({ children }: { children: React.ReactNode }) {
return (
<ChatStoreProvider store={store} source={host.messaging} gapFill={gapFill}>
{children}
</ChatStoreProvider>
);
}
function Thread({ conversationId }: { conversationId: string }) {
const { messages, status, hasOlder, loadOlder } = useMessages(conversationId);
// …
}
Reconnects, returning to the foreground and messages signals are still yours to hand to the gap-fill scheduler (gapFill.reconnected() and so on), see Overview · Using it in a host.
ChatStoreProvider
function ChatStoreProvider(props: ChatStoreProviderProps): ReactElement;
Hands the store to the components below it: creates a thread loader from its props, through which the hooks on this page read and fetch. The hooks on this page must be inside it and throw otherwise. When store, source, gapFill or requestCache becomes a different object, or newerPageLimit a different value, the loader is recreated and fetch state starts over.
ChatStoreProviderProps
interface ChatStoreProviderProps extends ChatThreadLoaderOptions {
conversations?: ChatConversationStore<ChatStoreConversationRow>;
readCursors?: ChatReadCursorStore;
children?: ReactNode;
}
The options for creating the thread loader (see ChatThreadLoaderOptions), plus the conversation store conversations that the conversation hooks read (optional; without it those hooks throw) and the children.
useChatStore
function useChatStore(): ChatStore;
Returns the store handed down by the Provider, for example to write through dispatch.
useMessages
function useMessages(conversationId: string): UseMessagesResult;
Reads a conversation's message window, with paging. The read state is the loader's getThread; mounting calls openThread and unmounting leaves, and paging and retrying are handed to the loader too (each behavior is on ChatThreadLoader). What shows in React:
- Correct on the first render. The first render reflects what the store holds right then, without waiting for an effect: a conversation loaded before is
readywith its messages at once, one never loaded isloading. For decisions that must be known on the render itself ("is this conversation in the store already"), readstatusfrom the first render. - Subscribing opens. The first
useMessagesof a conversation to mount opens it, and the last one to unmount leaves; StrictMode's "unmount and mount again right away" does not close and reopen. - The same data is fetched once. Several components reading the same conversation fetch one window and fill one gap; calling
loadOlderorloadNewerseveral times at once fetches once. - Re-renders only when the part read changed. Changes to other conversations and writes that change no data (such as a view hint) do not re-render; one write that changes many messages re-renders once.
UseMessagesResult
interface UseMessagesResult extends ChatThreadReadState {
retry(): void;
loadOlder(): Promise<void>;
loadNewer(): Promise<void>;
jumpTo(target: ChatMessageTarget, options?: ChatJumpOptions): Promise<ChatJumpResult>;
}
The return value of useMessages; the same object while nothing changed. The fields are those of ChatThreadReadState, plus four methods:
| Method | Description |
|---|---|
retry |
The loader's retry: redoes the step that failed; does nothing when nothing failed. |
loadOlder |
The loader's loadOlder: pages back. Rejects on failure, leaving the messages as they are. |
loadNewer |
The loader's loadNewer: pages forward. Rejects on failure, leaving the messages as they are. |
jumpTo |
The loader's jumpTo: jumps to a message, swapping in the window around it when it is not in the window; see Jumping to a message. The target is either the server's id or the client_msg_id of a message you sent. |
useMessage
function useMessage(conversationId: string, messageId: string): UseMessageResult;
Reads one message, for example to draw a quote bar. The read state is the loader's getMessage; mounting calls openMessage and unmounting leaves (behavior on ChatThreadLoader).
- When the message is in the conversation's in-memory window, returns the store's copy and re-renders as it updates; it does not re-render while that message is unchanged.
- Otherwise the loader calls
source.loadMessageonce; the fetched message is kept in the request result cache and does not follow live updates; once the message enters the window, the store's copy is used instead.
useMessageByClientId
function useMessageByClientId(conversationId: string, clientMessageId: string): UseMessageResult;
Reads a message you sent by client_msg_id, for example to follow its delivery state after sending and wait for it to be replaced by the server's copy. The read state is the loader's getMessageByClientId; it calls openMessageByClientId on mount and leaves on unmount (behavior in Reading one by client_msg_id).
- While it has not been replaced by the server's copy, it returns your local copy (sending, failed, blocked, or confirmed but not matched yet) and re-renders as its state changes.
- Once replaced, it returns the server's copy, as
useMessagedoes: the one in the store when it is in the window, otherwise fetched once by its id. - When the store has no such
client_msg_id,statusisreadyandmessageisundefined.
UseMessageResult
interface UseMessageResult extends ChatMessageReadState {
retry(): void;
}
The return value of useMessage and useMessageByClientId; the same object while nothing changed. The fields are those of ChatMessageReadState; retry is the loader's retryMessage (for useMessageByClientId, retryMessageByClientId), which fetches again after a failure and does nothing otherwise.
useConversationList
function useConversationList<C extends ChatStoreConversationRow = ChatStoreConversationRow>(): UseConversationListResult<C>;
Reads the conversation list, with paging. The read state is the conversation store's getList; mounting calls openList and unmounting leaves; paging, refetching and retrying go to the conversation store too (behaviour on ChatConversationStore). The first reader to mount fetches the first page; an invalidation refetches while there are readers. Re-renders only when the list's read state changed: writing another conversation by id does not re-render.
ChatStoreProvider must be given conversations (created by createChatConversationStore), otherwise it throws; the same goes for useConversation and useUnread. The type parameter C is the full shape of a conversation row, ChatStoreConversationRow when not given.
UseConversationListResult
interface UseConversationListResult<C extends ChatStoreConversationRow> extends ChatConversationListState<C> {
retry(): void;
loadMore(): Promise<void>;
refetch(): Promise<void>;
}
The return value of useConversationList; the same object while nothing changed. The fields are those of ChatConversationListState; retry is the conversation store's retryList, and loadMore and refetch are the conversation store's methods of the same names.
useConversation
function useConversation<C extends ChatStoreConversationRow = ChatStoreConversationRow>(conversationId: string): UseConversationResult<C>;
Reads one conversation. The read state is the conversation store's getConversation; mounting calls openConversation and unmounting leaves; retry is retryConversation. When it is in the store (fetched with the list or written by id) it is returned directly and re-renders when pin, hide, unread and the like change; when it is not in the current default list (including when the row is still cached but a refetch has dropped it from the list), the conversation store calls the source's loadConversation once and writes the result by id, without changing the list's content or order; listed tells you whether it is in the list. When the fetch returns undefined (it does not exist or cannot be seen), status is ready and conversation is undefined, and a reader arriving after all readers left fetches again; without loadConversation it waits for the first list page, and only when that page arrives without it is status ready with conversation undefined.
UseConversationResult
interface UseConversationResult<C extends ChatStoreConversationRow> extends ChatConversationReadState<C> {
retry(): void;
}
The return value of useConversation; the same object while nothing changed. The fields are those of ChatConversationReadState; retry is the conversation store's retryConversation, which fetches by id again after a failure and does nothing otherwise.
useUnread
function useUnread(conversationId: string): ChatUnreadState;
Reads the unread state of one conversation (ChatUnreadState): count, mention and lastReadSeq. Only subscribes and never fetches: when the store does not have the conversation, count is 0. Re-renders only when these three change.
useReadCursors
function useReadCursors(conversationId: string): ChatReadCursorState;
Reads one conversation's read cursors (ChatReadCursorState): your own read position and the other members' cursors for receipts. It only subscribes and never fetches: opening the conversation and fetching the snapshot is the loader's job (createChatReadCursorLoader). Re-renders only when this conversation's cursors change. ChatStoreProvider must be given readCursors (created by createChatReadCursorStore), otherwise it throws.
Differences from the SDK target
The target is these hooks re-exported by the SDK; this page follows today's source. The differences today:
- Only
useMessages,useMessage,useConversationanduseUnread(plususeMessageByClientIdanduseConversationList). The data the other hooks read (the total unread count, agent runs, typing, connection status) is not in the store yet. - The conversation hooks take a type parameter. The store package does not know the host's
ChatConversation, so the row type ofuseConversationListanduseConversationcomes from the caller; the SDK fixes it toChatConversationwhen it re-exports them. erroris the raw value the read method rejected with. The store package does not wrap it; when@openmaxai/chat-sdk/reactre-exports these hooks, the SDK wraps it into the SDK's error type, and that step is not in this package.- The Provider is the store package's own
ChatStoreProvider. Once the SDK's Provider is wired to the store, the hooks only need to sit inside the SDK's Provider. - Messages stay in memory after the last reader unmounts. Only gap fill is closed; "keep only the watermark" is not done yet.
- Paging back does not read local storage. The store does not read or write
ChatStorageyet; once the older end is unloaded, paging back waits for a read method that fetches byseq.
