feat(react): add newThreadId option to useStream for optimistic UI

Add optional newThreadId parameter to useStream hook that allows specifying
a thread ID for new thread creation while keeping threadId null. This enables
optimistic UI patterns where developers need to know the thread ID beforehand
for routing/navigation without causing 404 errors from attempting to fetch
non-existent thread history.

Usage:
- Set threadId: null and newThreadId: "predetermined-id"
- Submit message to create thread with specified ID
- Use onThreadId callback to update threadId after creation

This solves the UX problem of having to await thread creation before
enabling optimistic navigation to e.g. /[threadId] routes.
This commit is contained in:
MauritsBrinkman
2025-06-30 16:43:12 +02:00
committed by Tat Dat Duong
parent 03421c2b04
commit 8a763ad358
+10 -1
View File
@@ -516,6 +516,13 @@ export interface UseStreamOptions<
*/
threadId?: string | null;
/**
* The ID to use when creating a new thread. When provided, this ID will be used
* for thread creation when threadId is null. This enables optimistic UI updates
* where you know the thread ID before the thread is actually created.
*/
newThreadId?: string;
/**
* Callback that is called when the thread ID is updated (ie when a new thread is created).
*/
@@ -1013,7 +1020,9 @@ export function useStream<
let usableThreadId = threadId;
if (!usableThreadId) {
const thread = await client.threads.create();
const thread = await client.threads.create({
threadId: options.newThreadId,
});
onThreadId(thread.thread_id);
usableThreadId = thread.thread_id;
}