fix: async race condition in loadMails — responses from old folder were overwriting current folder

- When user switches folders quickly, multiple fetchMails requests are in flight
- Responses arrive out of order, last response wins regardless of which folder it was for
- Now loadMails checks selectedFolderIdRef before applying results
- Only updates mails state if the response is for the currently selected folder
This commit is contained in:
Agent Zero
2026-07-20 14:15:08 +02:00
parent 9946c6c4bd
commit 9ecd0e12c8
+19 -8
View File
@@ -152,23 +152,34 @@ export function MailPage() {
// Load mails when folder or page changes
const loadMails = useCallback(async () => {
if (!selectedFolderId) return;
const currentFolderId = selectedFolderId;
setLoadingMails(true);
try {
if (searchQuery.trim()) {
const result = await searchMails(searchQuery);
setMails(result.mails);
setMailsTotal(result.total);
// Only update if still on the same folder
if (selectedFolderIdRef.current === currentFolderId) {
setMails(result.mails);
setMailsTotal(result.total);
}
} else {
const result = await fetchMails(selectedFolderId, mailsPage, sortBy, sortOrder);
setMails(result.mails);
setMailsTotal(result.total);
const result = await fetchMails(currentFolderId, mailsPage, sortBy, sortOrder);
// Only update if still on the same folder
if (selectedFolderIdRef.current === currentFolderId) {
setMails(result.mails);
setMailsTotal(result.total);
}
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
setError(msg);
setMails([]);
if (selectedFolderIdRef.current === currentFolderId) {
setError(msg);
setMails([]);
}
}
if (selectedFolderIdRef.current === currentFolderId) {
setLoadingMails(false);
}
setLoadingMails(false);
}, [selectedFolderId, mailsPage, searchQuery, sortBy, sortOrder]);
useEffect(() => {