Skip to content

Commit

Permalink
Update $id.tsx
Browse files Browse the repository at this point in the history
  • Loading branch information
AtlantisPleb committed Feb 22, 2025
1 parent d04e061 commit 6b8effa
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions frontend/app/routes/chat/$id.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ export default function ChatSession() {
const { setMessages } = useMessagesStore();
const messageContainerRef = useRef<HTMLDivElement>(null);

// Create stable refs for callbacks
const setMessagesRef = useRef(setMessages);
setMessagesRef.current = setMessages;

// Use the cached empty array to avoid returning a new array on every call.
const messagesSelector = useCallback(
(state) => state.messages[id || ""] || EMPTY_MESSAGES,
Expand Down Expand Up @@ -42,11 +46,13 @@ export default function ChatSession() {
useEffect(() => {
if (!id) return;

// Add a small delay to allow the conversation to be created
const timeout = setTimeout(async () => {
const controller = new AbortController();

const loadMessages = async () => {
try {
const response = await fetch(`/api/conversations/${id}/messages`, {
credentials: "include", // Include cookies in the request
credentials: "include",
signal: controller.signal,
headers: {
"Accept": "application/json",
},
Expand All @@ -59,14 +65,17 @@ export default function ChatSession() {
throw new Error("Failed to load messages");
}
const data = await response.json();
setMessages(id, data);
setMessagesRef.current(id, data);
} catch (error) {
console.error("Error loading messages:", error);
if (!controller.signal.aborted) {
console.error("Error loading messages:", error);
}
}
}, 500); // 500ms delay
};

return () => clearTimeout(timeout);
}, [id, setMessages]);
loadMessages();
return () => controller.abort();
}, [id]);

const handleSubmit = async (message: string, repos?: string[]) => {
try {
Expand Down Expand Up @@ -129,6 +138,11 @@ export default function ChatSession() {
{state.pendingChanges} pending changes to sync
</div>
)}
{state.error && (
<div className="mt-2 text-sm text-red-500">
Error: {state.error}
</div>
)}
</div>
</div>
);
Expand Down

0 comments on commit 6b8effa

Please sign in to comment.