here’s my code:
the problem is when i set chat this way, the new message that child component get won’t be updated except the first time and the finish time
import { useParams } from "@umijs/max";
import { type CustomTransport } from "@/libs/ai/transport";
import { getChatHistory } from "@/libs/api";
import { Chat } from "@ai-sdk/react";
import { useQuery } from "@tanstack/react-query";
import type { UIMessage } from "ai";
import {
type ReactNode,
createContext,
useContext,
useEffect,
useState,
} from "react";
interface ChatContextValue {
chat: Chat<UIMessage>;
clearChat: () => void;
transport: CustomTransport;
loadingMessage?: boolean;
}
const ChatContext = createContext<ChatContextValue | undefined>(undefined);
const createChat = (opts: ChatOptsType) => new Chat<UIMessage>(opts);
type ChatOptsType = ConstructorParameters<typeof Chat>[0];
export const ChatProvider = ({
children,
chatOpts,
}: {
children: ReactNode;
chatOpts: ChatOptsType & {
transport: CustomTransport;
};
}) => {
const { id } = useParams();
const [chat, setChat] = useState(() => createChat(chatOpts));
const { data, isSuccess } = useQuery({
queryKey: ["chatHistory", id],
queryFn: () => getChatHistory(id!),
retry: false,
});
useEffect(() => {
if (isSuccess ) {
setChat(
createChat({
...chatOpts,
messages: data.messages,
}),
);
}
}, [isSuccess, data, chatOpts, setChat]);
const clearChat = () => {
setChat(createChat(chatOpts));
};
return (
<ChatContext.Provider
value={{
chat,
clearChat,
transport: chatOpts.transport,
}}
>
{children}
</ChatContext.Provider>
);
};
export function useSharedChatContext() {
const context = useContext(ChatContext);
if (!context) {
throw new Error("useSharedChatContext must be used within a ChatProvider");
}
return context;
}
Hey @hoon! Just checking in to see if you still need help with loading messages in your shared chat context. Have you found a solution, or do you want to dive deeper into this together? Let’s figure this out!