Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 31x 31x 31x 31x 31x 31x 57x 57x 57x 57x 57x 57x 57x 57x 57x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 22x 22x 22x 24x 24x 24x 24x 24x 24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 57x 57x 57x 57x 57x 57x 57x 57x 2x 2x 2x 2x 57x 27x 1x 1x 26x 27x 57x 57x 57x 2x 1x 57x 57x 57x 2x 2x 2x 2x 2x 2x 57x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 57x 57x 2x 2x 2x 2x 2x 2x 2x 2x 2x 57x 57x 57x 1x 1x 1x 1x 1x 1x 57x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 57x 57x 1x 1x 1x 1x 1x 1x 1x 1x 1x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 2x 2x 2x 57x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 57x 57x 2x 2x 2x 2x 57x 57x 57x 2x 2x 2x 57x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 57x 57x 2x 2x 2x 2x 2x 57x 57x 57x 1x 1x 1x 1x 57x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 57x 57x 1x 1x 1x 57x 57x 57x 57x 57x 57x 57x 57x 57x 2x 2x 57x 2x 2x 57x 57x 57x 2x 2x 2x 1x 2x 57x 2x 2x 2x 2x 2x 57x 57x 57x 57x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 57x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 57x 57x 1x 1x 1x 1x 1x 57x 1x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 2x 2x 2x 2x 2x 57x 57x 57x 57x 1x 1x 1x 1x 1x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 2x 2x 2x 2x 2x 57x 57x 57x 57x 2x 2x 2x 2x 2x 57x 57x 57x 57x 1x 1x 1x 1x 1x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x | import {
MutateOptions,
QueryObserverResult,
RefetchOptions,
UseMutateAsyncFunction,
useMutation,
useQuery,
useQueryClient,
} from '@tanstack/react-query';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useLogger } from '@common/utils/logger/useLogger';
import { normalizeNewsletterFilter } from '@common/utils/newsletterUtils';
import { useAuth } from '../contexts/AuthContext';
import { newsletterService, readingQueueService } from '../services';
import { optimizedNewsletterService } from '../services/optimizedNewsletterService';
import { NewsletterWithRelations, ReadingQueueItem } from '../types';
import { PaginatedResponse } from '../types/api';
import type { NewsletterFilter } from '../types/cache';
import {
cancelQueries,
getCacheManager,
getQueryData,
SimpleCacheManager,
} from '../utils/cacheUtils';
import { invalidateForOperation } from '../utils/optimizedCacheInvalidation';
import { queryKeyFactory } from '../utils/queryKeyFactory';
import { updateNewsletterTags } from '../utils/tagUtils';
type PreviousNewslettersState = {
previousNewsletters?: NewsletterWithRelations[];
previousNewsletter?: NewsletterWithRelations;
deletedIds?: string[];
rollbackFunctions?: Array<() => void>;
newsletter?: NewsletterWithRelations;
newArchivedState?: boolean;
shouldRemoveFromView?: boolean;
};
// Cache configuration based on data volatility
const CACHE_CONFIG = {
// Newsletter list data - moderately dynamic
LIST_STALE_TIME: 2 * 60 * 1000, // 2 minutes - data can be slightly stale
LIST_CACHE_TIME: 10 * 60 * 1000, // 10 minutes - keep in memory longer
// Individual newsletter details - less dynamic
DETAIL_STALE_TIME: 5 * 60 * 1000, // 5 minutes - details change less frequently
DETAIL_CACHE_TIME: 15 * 60 * 1000, // 15 minutes - keep longer for navigation
// Error retry configuration
RETRY_DELAY_BASE: 1000, // 1 second base delay
MAX_RETRY_DELAY: 30000, // 30 second max delay
MAX_RETRIES: 3,
};
// Utility function for safe predicate checks
const createSafePredicate = (ids: string[] | undefined) => (query: { queryKey: unknown[] }) => {
if (!ids || !Array.isArray(ids)) {
return (
queryKeyFactory.matchers.isNewsletterListKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterInfiniteKey(query.queryKey as unknown[])
);
}
return (
queryKeyFactory.matchers.isNewsletterListKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterInfiniteKey(query.queryKey as unknown[]) ||
ids.some((id) =>
queryKeyFactory.matchers.isNewsletterDetailKey(query.queryKey as unknown[], id)
)
);
};
interface UseNewslettersReturn {
// Single newsletter operations
getNewsletter: (id: string) => Promise<NewsletterWithRelations | null>;
// Newsletter list and query
newsletters: NewsletterWithRelations[];
isLoadingNewsletters: boolean;
isErrorNewsletters: boolean;
errorNewsletters: Error | null;
refetchNewsletters: (
options?: RefetchOptions
) => Promise<QueryObserverResult<PaginatedResponse<NewsletterWithRelations>, Error>>;
// Read status mutations
markAsRead: UseMutateAsyncFunction<boolean, Error, string, PreviousNewslettersState>;
isMarkingAsRead: boolean;
errorMarkingAsRead: Error | null;
markAsUnread: UseMutateAsyncFunction<boolean, Error, string, PreviousNewslettersState>;
isMarkingAsUnread: boolean;
errorMarkingAsUnread: Error | null;
bulkMarkAsRead: UseMutateAsyncFunction<boolean, Error, string[], PreviousNewslettersState>;
isBulkMarkingAsRead: boolean;
errorBulkMarkingAsRead: Error | null;
bulkMarkAsUnread: UseMutateAsyncFunction<boolean, Error, string[], PreviousNewslettersState>;
isBulkMarkingAsUnread: boolean;
errorBulkMarkingAsUnread: Error | null;
// Like mutations
toggleLike: UseMutateAsyncFunction<boolean, Error, string, PreviousNewslettersState>;
isTogglingLike: boolean;
errorTogglingLike: Error | null;
// Archive mutations
toggleArchive: UseMutateAsyncFunction<boolean, Error, string, PreviousNewslettersState>;
bulkArchive: UseMutateAsyncFunction<boolean, Error, string[], PreviousNewslettersState>;
bulkUnarchive: UseMutateAsyncFunction<boolean, Error, string[], PreviousNewslettersState>;
isArchiving: boolean;
errorArchiving: Error | null;
isUnarchiving: boolean;
errorUnarchiving: Error | null;
isBulkArchiving: boolean;
errorBulkArchiving: Error | null;
isBulkUnarchiving: boolean;
errorBulkUnarchiving: Error | null;
// Queue mutations
toggleInQueue: UseMutateAsyncFunction<boolean, Error, string, unknown>;
isTogglingInQueue: boolean;
errorTogglingInQueue: Error | null;
// Delete mutations
deleteNewsletter: UseMutateAsyncFunction<boolean, Error, string, unknown>;
isDeletingNewsletter: boolean;
errorDeletingNewsletter: Error | null;
bulkDeleteNewsletters: UseMutateAsyncFunction<boolean, Error, string[], unknown>;
isBulkDeletingNewsletters: boolean;
errorBulkDeletingNewsletters: Error | null;
// Tag mutations
updateNewsletterTags: (
id: string,
tagIds: string[],
options?: MutateOptions<
boolean,
Error,
{ id: string; tagIds: string[] },
PreviousNewslettersState
>
) => Promise<void>;
isUpdatingTags: boolean;
errorUpdatingTags: Error | null;
}
export const useNewsletters = (
filters: NewsletterFilter = {},
options: {
enabled?: boolean;
refetchOnWindowFocus?: boolean;
staleTime?: number;
cacheTime?: number;
debug?: boolean;
} = {}
): UseNewslettersReturn => {
const { user } = useAuth();
const log = useLogger('useNewsletters');
const queryClient = useQueryClient();
const lastCallTimeRef = useRef<number>(0);
const {
enabled = true,
refetchOnWindowFocus = false,
staleTime = CACHE_CONFIG.LIST_STALE_TIME,
cacheTime = CACHE_CONFIG.LIST_CACHE_TIME,
// debug = false, // Commented out unused parameter
} = options;
// Create cache manager instance with proper null check
const cacheManager = useMemo(() => {
try {
return getCacheManager() as SimpleCacheManager;
} catch (error) {
log.error('Failed to initialize cache manager', { error });
throw new Error('Cache manager initialization failed');
}
}, [log]);
// Normalize filters to camelCase for query and cache
const normalizedFilters = useMemo(() => normalizeNewsletterFilter(filters), [filters]);
// Generate query key with normalized filters
const queryKey = useMemo(
() => queryKeyFactory.newsletters.list(normalizedFilters),
[normalizedFilters]
);
// Define proper type for query parameters
interface QueryParams {
search?: string;
isRead?: boolean;
isArchived?: boolean;
isLiked?: boolean;
tagIds?: string[];
sourceIds?: string[];
dateFrom?: string;
dateTo?: string;
limit?: number;
offset?: number;
orderBy?: string;
ascending?: boolean;
}
// Build API query parameters from normalized filters with proper typing
const queryParams = useMemo<QueryParams>(() => {
const params: QueryParams = {
search: normalizedFilters.search,
isRead: normalizedFilters.isRead,
isArchived: normalizedFilters.isArchived,
isLiked: normalizedFilters.isLiked,
tagIds: normalizedFilters.tagIds,
sourceIds: normalizedFilters.sourceIds,
dateFrom: normalizedFilters.dateFrom,
dateTo: normalizedFilters.dateTo,
limit: normalizedFilters.limit || 50,
offset: normalizedFilters.offset || 0,
orderBy: normalizedFilters.orderBy || 'received_at',
ascending: normalizedFilters.ascending ?? false,
};
// Validate source IDs in development
if (process.env.NODE_ENV === 'development') {
const sourceIds: string[] | undefined = normalizedFilters.sourceIds;
if (sourceIds && sourceIds.length > 0) {
const validSourceIds = sourceIds.filter(
(id: string): id is string => typeof id === 'string' && id.length > 0
);
if (validSourceIds.length !== sourceIds.length) {
log.warn('Invalid source IDs detected', {
action: 'validate_source_ids',
metadata: {
original: sourceIds,
valid: validSourceIds,
},
});
}
}
}
return params;
}, [normalizedFilters, log]);
// Track query key changes to prevent unnecessary re-fetches
const previousQueryKeyRef = useRef<string>('');
const queryKeyString = JSON.stringify(queryKey);
useEffect(() => {
// Only track if query key actually changed
if (previousQueryKeyRef.current !== queryKeyString) {
const now = Date.now();
const timeSinceLastCall = now - lastCallTimeRef.current;
if (lastCallTimeRef.current > 0 && timeSinceLastCall < 1000) {
log.warn('Frequent newsletter query detected', {
action: 'frequency_warning',
metadata: {
timeSinceLastCall,
queryKey: queryKeyString,
userId: user?.id,
previousKey: previousQueryKeyRef.current,
},
});
}
lastCallTimeRef.current = now;
previousQueryKeyRef.current = queryKeyString;
}
}, [queryKeyString, log, user?.id]);
// Main newsletters query using the new API with proper type annotation
const {
data: newslettersResponse,
isLoading,
error: errorNewsletters,
refetch: refetchNewsletters,
} = useQuery<PaginatedResponse<NewsletterWithRelations>, Error>({
queryKey,
queryFn: async (): Promise<PaginatedResponse<NewsletterWithRelations>> => {
try {
log.debug('Executing newsletter API call', {
action: 'api_call_start',
metadata: {
queryParams,
queryKey: JSON.stringify(queryKey),
},
});
const result = await optimizedNewsletterService.getAll(queryParams);
// Type guard to ensure result.data exists
if (!result?.data) {
throw new Error('No data received from API');
}
// Validate source filtering in development
if (process.env.NODE_ENV === 'development' && queryParams.sourceIds?.length) {
const unexpectedSources = result.data.filter(
(newsletter) =>
newsletter.newsletter_source_id &&
!queryParams.sourceIds!.includes(newsletter.newsletter_source_id)
);
if (unexpectedSources.length > 0) {
log.warn('Source filtering may not be working correctly', {
action: 'validate_source_filtering',
metadata: {
expectedSources: queryParams.sourceIds,
unexpectedItems: unexpectedSources.map((n) => ({
id: n.id,
sourceId: n.newsletter_source_id,
sourceName: n.source?.name,
})),
},
});
}
}
log.debug('Newsletter API call completed', {
action: 'api_call_success',
metadata: {
dataCount: result.data?.length || 0,
totalCount: result.count,
},
});
return result;
} catch (error) {
const errorMessage = error instanceof Error ? error : new Error(String(error));
log.error(
'API Error occurred',
{
action: 'fetch_newsletters',
metadata: { filters, queryParams },
},
errorMessage
);
throw errorMessage;
}
},
enabled: enabled && !!user,
staleTime,
gcTime: cacheTime,
refetchOnWindowFocus,
refetchOnMount: false,
refetchOnReconnect: false,
retry: CACHE_CONFIG.MAX_RETRIES,
retryDelay: (attemptIndex) =>
Math.min(
CACHE_CONFIG.RETRY_DELAY_BASE * Math.pow(2, attemptIndex),
CACHE_CONFIG.MAX_RETRY_DELAY
),
// Prevent unnecessary refetches
structuralSharing: (oldData, newData) => {
// If data hasn't structurally changed, return old reference
if (JSON.stringify(oldData) === JSON.stringify(newData)) {
return oldData;
}
return newData;
},
});
// Safe access to newsletters data
const newsletters = useMemo(() => newslettersResponse?.data || [], [newslettersResponse]);
// Get single newsletter function - memoized to prevent recreation
const getNewsletter = useCallback(async (id: string): Promise<NewsletterWithRelations | null> => {
if (!id) return null;
return newsletterService.getById(id);
}, []);
// Mark as read mutation with proper typing
const markAsReadMutation = useMutation<boolean, Error, string, PreviousNewslettersState>({
mutationFn: async (id: string): Promise<boolean> => {
if (!id) {
throw new Error('Newsletter ID is required');
}
try {
await newsletterService.markAsRead(id);
return true;
} catch (error) {
const errorMessage = error instanceof Error ? error : new Error(String(error));
log.error('Failed to mark as read', { id }, errorMessage);
throw errorMessage;
}
},
onMutate: async (id: string) => {
if (!id) {
throw new Error('Newsletter ID is required for optimistic update');
}
// Cancel any outgoing refetches to avoid overwriting our optimistic update
await cancelQueries({
predicate: (query) =>
queryKeyFactory.matchers.isNewsletterListKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterInfiniteKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterDetailKey(query.queryKey as unknown[], id),
});
const previousNewsletters = getQueryData<NewsletterWithRelations[]>(queryKey) || [];
// Optimistically update the cache
cacheManager.updateNewsletterInCache({
id,
updates: {
is_read: true,
updated_at: new Date().toISOString(),
},
});
// Return the context with previous values for potential rollback
return { previousNewsletters };
},
onError: (error: Error, id: string, context?: PreviousNewslettersState) => {
log.error('Error in markAsRead mutation', { id }, error);
// Rollback to previous state on error
if (context?.previousNewsletters) {
const newsletter = context.previousNewsletters.find((n) => n.id === id);
if (newsletter) {
cacheManager.updateNewsletterInCache({
id,
updates: {
is_read: newsletter.is_read,
updated_at: newsletter.updated_at,
},
});
}
}
},
onSettled: (_data: boolean | undefined, error: Error | null, id: string) => {
// Invalidate and refetch related queries
if (!error) {
// Use invalidateForOperation to properly update UI
invalidateForOperation(queryClient, 'mark-read', [id]);
// Update unread count optimistically for immediate feedback
cacheManager.updateUnreadCountOptimistically({
type: 'mark-read',
newsletterIds: [id],
});
// Notify other components about the read status change
window.dispatchEvent(new CustomEvent('newsletter:read-status-changed'));
}
},
});
// Mark as unread mutation with proper typing
const markAsUnreadMutation = useMutation<boolean, Error, string, PreviousNewslettersState>({
mutationFn: async (id: string): Promise<boolean> => {
if (!id) {
throw new Error('Newsletter ID is required');
}
try {
await newsletterService.markAsUnread(id);
return true;
} catch (error) {
const errorMessage = error instanceof Error ? error : new Error(String(error));
log.error('Failed to mark as unread', { id }, errorMessage);
throw errorMessage;
}
},
onMutate: async (id: string) => {
if (!id) {
throw new Error('Newsletter ID is required for optimistic update');
}
await cancelQueries({
predicate: (query) =>
queryKeyFactory.matchers.isNewsletterListKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterInfiniteKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterDetailKey(query.queryKey as unknown[], id),
});
const previousNewsletters = getQueryData<NewsletterWithRelations[]>(queryKey) || [];
// Optimistically update the cache
cacheManager.updateNewsletterInCache({
id,
updates: {
is_read: false,
updated_at: new Date().toISOString(),
},
});
return { previousNewsletters };
},
onError: (error: Error, id: string, context?: PreviousNewslettersState) => {
log.error('Error in markAsUnread mutation', { id }, error);
// Rollback to previous state on error
if (context?.previousNewsletters) {
const newsletter = context.previousNewsletters.find((n) => n.id === id);
if (newsletter) {
cacheManager.updateNewsletterInCache({
id,
updates: {
is_read: newsletter.is_read,
updated_at: newsletter.updated_at,
},
});
}
}
},
onSettled: (_data: boolean | undefined, error: Error | null, id: string) => {
// Invalidate and refetch related queries
if (!error) {
// Use invalidateForOperation to properly update UI
invalidateForOperation(queryClient, 'mark-unread', [id]);
// Update unread count optimistically for immediate feedback
cacheManager.updateUnreadCountOptimistically({
type: 'mark-unread',
newsletterIds: [id],
});
// Notify other components about the read status change
window.dispatchEvent(new CustomEvent('newsletter:read-status-changed'));
}
},
});
// Bulk mark as read mutation with enhanced type safety
const bulkMarkAsReadMutation = useMutation<boolean, Error, string[], PreviousNewslettersState>({
mutationFn: async (ids: string[]): Promise<boolean> => {
if (!ids?.length) {
throw new Error('No newsletter IDs provided for bulk mark as read');
}
try {
const result = await newsletterService.bulkUpdate({
ids,
updates: { is_read: true },
});
if (result.successCount !== ids.length) {
throw new Error('Failed to mark all newsletters as read');
}
return true;
} catch (error) {
const errorMessage = error instanceof Error ? error : new Error(String(error));
log.error('Bulk mark as read failed', { ids, count: ids.length }, errorMessage);
throw errorMessage;
}
},
onMutate: async (ids: string[]): Promise<PreviousNewslettersState> => {
if (!ids?.length) {
throw new Error('No newsletter IDs provided for optimistic update');
}
// Cancel any outgoing refetches to avoid overwriting our optimistic update
await cancelQueries({
predicate: createSafePredicate(ids),
});
const previousNewsletters = getQueryData<NewsletterWithRelations[]>(queryKey) || [];
const now = new Date().toISOString();
// Optimistically update the cache
cacheManager.batchUpdateNewsletters(
ids.map((id) => ({
id,
updates: { is_read: true, updated_at: now },
}))
);
return { previousNewsletters };
},
onError: (error: Error, ids: string[], context?: PreviousNewslettersState) => {
log.error('Error in bulkMarkAsRead mutation', { ids, count: ids.length }, error);
// Rollback to previous state on error
if (context?.previousNewsletters) {
ids.forEach((id) => {
const newsletter = context.previousNewsletters!.find((n) => n.id === id);
if (newsletter) {
cacheManager.updateNewsletterInCache({
id,
updates: {
is_read: newsletter.is_read,
updated_at: newsletter.updated_at,
},
});
}
});
}
},
onSettled: (_data: boolean | undefined, error: Error | null, ids: string[]) => {
// Invalidate and refetch related queries
if (!error) {
// Use invalidateForOperation to properly update UI
invalidateForOperation(queryClient, 'bulk-mark-read', ids);
// Update unread count optimistically for immediate feedback
cacheManager.updateUnreadCountOptimistically({
type: 'bulk-mark-read',
newsletterIds: ids,
});
// Notify other components about the read status change
window.dispatchEvent(new CustomEvent('newsletter:read-status-changed'));
}
},
});
// Bulk mark as unread mutation with enhanced type safety
const bulkMarkAsUnreadMutation = useMutation<boolean, Error, string[], PreviousNewslettersState>({
mutationFn: async (ids: string[]): Promise<boolean> => {
if (!ids?.length) {
throw new Error('No newsletter IDs provided for bulk mark as unread');
}
try {
const result = await newsletterService.bulkUpdate({
ids,
updates: { is_read: false },
});
if (result.successCount !== ids.length) {
throw new Error('Failed to mark all newsletters as unread');
}
return true;
} catch (error) {
const errorMessage = error instanceof Error ? error : new Error(String(error));
log.error('Bulk mark as unread failed', { ids, count: ids.length }, errorMessage);
throw errorMessage;
}
},
onMutate: async (ids: string[]): Promise<PreviousNewslettersState> => {
if (!ids?.length) {
throw new Error('No newsletter IDs provided for optimistic update');
}
// Cancel any outgoing refetches
await cancelQueries({
predicate: createSafePredicate(ids),
});
const previousNewsletters = getQueryData<NewsletterWithRelations[]>(queryKey) || [];
const now = new Date().toISOString();
// Optimistically update the cache
cacheManager.batchUpdateNewsletters(
ids.map((id) => ({
id,
updates: { is_read: false, updated_at: now },
}))
);
return { previousNewsletters };
},
onError: (error: Error, ids: string[], context?: PreviousNewslettersState) => {
log.error('Error in bulkMarkAsUnread mutation', { ids, count: ids.length }, error);
// Rollback to previous state on error
if (context?.previousNewsletters) {
ids.forEach((id) => {
const newsletter = context.previousNewsletters!.find((n) => n.id === id);
if (newsletter) {
cacheManager.updateNewsletterInCache({
id,
updates: {
is_read: newsletter.is_read,
updated_at: newsletter.updated_at,
},
});
}
});
}
},
onSettled: (_data: boolean | undefined, error: Error | null, ids: string[]) => {
// Invalidate and refetch related queries
if (!error) {
// Use invalidateForOperation to properly update UI
invalidateForOperation(queryClient, 'bulk-mark-unread', ids);
// Update unread count optimistically for immediate feedback
cacheManager.updateUnreadCountOptimistically({
type: 'bulk-mark-unread',
newsletterIds: ids,
});
// Notify other components about the read status change
window.dispatchEvent(new CustomEvent('newsletter:read-status-changed'));
}
},
});
// Toggle like mutation
const toggleLikeMutation = useMutation<boolean, Error, string, PreviousNewslettersState>({
mutationFn: async (id: string) => {
await newsletterService.toggleLike(id);
return true;
},
onMutate: async (id) => {
await cancelQueries({
predicate: (query) =>
queryKeyFactory.matchers.isNewsletterListKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterInfiniteKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterDetailKey(query.queryKey as unknown[], id),
});
const queryData = getQueryData<PaginatedResponse<NewsletterWithRelations>>(queryKey);
const previousNewsletters = queryData?.data || [];
// Find the current newsletter to get its like status
const currentNewsletter = previousNewsletters.find(
(n: NewsletterWithRelations) => n.id === id
);
const currentLikedState = currentNewsletter?.is_liked ?? false;
const newLikedState = !currentLikedState;
console.log(
`Optimistically toggling like for newsletter ${id}: ${currentLikedState} -> ${newLikedState}`
);
cacheManager.updateNewsletterInCache({
id,
updates: {
is_liked: newLikedState,
updated_at: new Date().toISOString(),
},
});
return { previousNewsletters };
},
onError: (_err, id, context) => {
console.log(`Error in toggleLike for newsletter ${id}, rolling back`);
if (context?.previousNewsletters) {
const newsletter = context.previousNewsletters.find((n) => n.id === id);
if (newsletter) {
cacheManager.updateNewsletterInCache({
id,
updates: {
is_liked: newsletter.is_liked,
updated_at: newsletter.updated_at,
},
});
}
}
},
onSettled: (_data: boolean | undefined, error: Error | null, id: string) => {
// Invalidate and refetch related queries
if (!error) {
// Use invalidateForOperation to properly update UI
invalidateForOperation(queryClient, 'toggle-like', [id]);
}
},
});
// Toggle archive mutation
const toggleArchiveMutation = useMutation<boolean, Error, string, PreviousNewslettersState>({
mutationFn: async (id: string) => {
await newsletterService.toggleArchive(id);
return true;
},
onMutate: async (id) => {
// Cancel any outgoing refetches to avoid race conditions
await cancelQueries({
predicate: (query) =>
queryKeyFactory.matchers.isNewsletterListKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterInfiniteKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterDetailKey(query.queryKey as unknown[], id),
});
// Get the current newsletter list data to understand the current filter context
const queryData = getQueryData<PaginatedResponse<NewsletterWithRelations>>(queryKey);
const previousNewsletters = Array.isArray(queryData?.data)
? queryData.data
: Array.isArray(queryData)
? queryData
: [];
const newsletter = previousNewsletters.find((n: NewsletterWithRelations) => n.id === id);
if (!newsletter) {
return { previousNewsletters };
}
const newArchivedState = !newsletter.is_archived;
// Determine if we should remove the newsletter from the current view
const currentFilter = normalizedFilters;
const shouldRemoveFromView =
newArchivedState && // Newsletter is being archived
(currentFilter.isArchived === false || currentFilter.isArchived === undefined); // And we're not in archived view
if (shouldRemoveFromView) {
// Remove the newsletter from the current filtered view immediately
// Handle both infinite queries and regular list queries
cacheManager.queryClient.setQueriesData(
{
predicate: (query) => {
const key = query.queryKey;
return (
Array.isArray(key) &&
key[0] === 'newsletters' &&
(key[1] === 'infinite' || key[1] === 'list')
);
},
},
(
oldData:
| { pages: PaginatedResponse<NewsletterWithRelations>[] }
| PaginatedResponse<NewsletterWithRelations>
| undefined
) => {
// Handle infinite query data structure
if (oldData && 'pages' in oldData && oldData.pages) {
let totalRemoved = 0;
const updatedData = {
...oldData,
pages: oldData.pages.map((page) => {
const filteredData = page.data.filter(
(newsletter: NewsletterWithRelations) => newsletter.id !== id
);
const removed = page.data.length - filteredData.length;
totalRemoved += removed;
return {
...page,
data: filteredData,
count: Math.max(0, (page.count || 0) - removed),
};
}),
};
// Log the removal for debugging
if (totalRemoved > 0) {
console.log(
`Removed ${totalRemoved} archived newsletter(s) from infinite query cache`
);
}
return updatedData;
}
// Handle regular list query data structure
if (oldData && 'data' in oldData && Array.isArray(oldData.data)) {
const filteredData = oldData.data.filter(
(newsletter: NewsletterWithRelations) => newsletter.id !== id
);
const removed = oldData.data.length - filteredData.length;
if (removed > 0) {
console.log(`Removed ${removed} archived newsletter(s) from list query cache`);
}
return {
...oldData,
data: filteredData,
count: Math.max(0, (oldData.count || 0) - removed),
};
}
return oldData;
}
);
} else {
// Update the newsletter's archived status in place
cacheManager.updateNewsletterInCache({
id,
updates: {
is_archived: newArchivedState,
updated_at: new Date().toISOString(),
},
});
}
// Return the previous state in case we need to rollback
return {
previousNewsletters,
newsletter,
newArchivedState,
shouldRemoveFromView,
};
},
onError: (_err, id, context) => {
// Rollback to the previous state on error
if (context?.previousNewsletters && context?.newsletter) {
if (context.shouldRemoveFromView) {
// Restore the newsletter to the list if it was removed
cacheManager.queryClient.setQueryData(
queryKey,
(oldData: PaginatedResponse<NewsletterWithRelations>) => {
if (!oldData || !oldData.data || !Array.isArray(oldData.data)) return oldData;
// Add the newsletter back to its original position
const restoredData = [...oldData.data];
const originalIndex = context.previousNewsletters!.findIndex((n) => n.id === id);
if (originalIndex >= 0) {
restoredData.splice(originalIndex, 0, context.newsletter!);
} else {
restoredData.unshift(context.newsletter!);
}
return {
...oldData,
data: restoredData,
count: (oldData.count || 0) + 1,
};
}
);
} else {
// Restore the original archived state
cacheManager.updateNewsletterInCache({
id,
updates: {
is_archived: context.newsletter.is_archived,
updated_at: context.newsletter.updated_at,
},
});
}
}
},
onSettled: (_data, _error, id) => {
// Use invalidateForOperation to properly update UI
if (!_error) {
invalidateForOperation(queryClient, 'toggle-archive', [id]);
// Dispatch event for unread count updates
window.dispatchEvent(new CustomEvent('newsletter:archived'));
}
},
});
// Bulk archive mutation
const bulkArchiveMutation = useMutation<boolean, Error, string[], PreviousNewslettersState>({
mutationFn: async (ids: string[]) => {
if (!ids || !Array.isArray(ids) || ids.length === 0) {
throw new Error('Invalid or empty newsletter IDs provided for bulk archive');
}
const result = await newsletterService.bulkArchive(ids);
return result.successCount === ids.length;
},
onMutate: async (ids) => {
await cancelQueries({
predicate: createSafePredicate(ids),
});
const queryData = getQueryData<PaginatedResponse<NewsletterWithRelations>>(queryKey);
const previousNewsletters = Array.isArray(queryData?.data)
? queryData.data
: Array.isArray(queryData)
? queryData
: [];
// Determine if we should remove newsletters from the current view
const currentFilter = normalizedFilters;
const shouldRemoveFromView =
currentFilter.isArchived === false || currentFilter.isArchived === undefined; // Not in archived view
if (shouldRemoveFromView) {
// Remove archived newsletters from both infinite queries and regular list queries
cacheManager.queryClient.setQueriesData(
{
predicate: (query) => {
const key = query.queryKey;
return (
Array.isArray(key) &&
key[0] === 'newsletters' &&
(key[1] === 'infinite' || key[1] === 'list')
);
},
},
(oldData: { pages: PaginatedResponse<NewsletterWithRelations>[] } | undefined) => {
if (!oldData || !oldData.pages) return oldData;
let totalRemoved = 0;
const updatedData = {
...oldData,
pages: oldData.pages.map((page) => {
const filteredData = page.data.filter(
(newsletter: NewsletterWithRelations) => !ids.includes(newsletter.id)
);
const removed = page.data.length - filteredData.length;
totalRemoved += removed;
return {
...page,
data: filteredData,
count: Math.max(0, (page.count || 0) - removed),
};
}),
};
// Log the removal for debugging
if (totalRemoved > 0) {
console.log(
`Removed ${totalRemoved} archived newsletter(s) from infinite query cache`
);
}
return updatedData;
}
);
} else {
// Update the newsletters' archived status in place
cacheManager.batchUpdateNewsletters(
ids.map((id) => ({
id,
updates: {
is_archived: true,
updated_at: new Date().toISOString(),
},
}))
);
}
return { previousNewsletters };
},
onError: (_err, ids, context) => {
if (context?.previousNewsletters) {
ids.forEach((id) => {
const newsletter = context.previousNewsletters!.find((n) => n.id === id);
if (newsletter) {
cacheManager.updateNewsletterInCache({
id,
updates: {
is_archived: newsletter.is_archived,
updated_at: newsletter.updated_at,
},
});
}
});
}
},
onSettled: (_data, _error, ids) => {
invalidateForOperation(queryClient, 'bulk-archive', ids);
// Dispatch event for unread count updates
window.dispatchEvent(new CustomEvent('newsletter:archived'));
},
});
// Bulk unarchive mutation
const bulkUnarchiveMutation = useMutation<boolean, Error, string[], PreviousNewslettersState>({
mutationFn: async (ids: string[]) => {
if (!ids || !Array.isArray(ids) || ids.length === 0) {
throw new Error('Invalid or empty newsletter IDs provided for bulk unarchive');
}
const result = await newsletterService.bulkUnarchive(ids);
return result.successCount === ids.length;
},
onMutate: async (ids) => {
await cancelQueries({
predicate: createSafePredicate(ids),
});
const queryData = getQueryData<PaginatedResponse<NewsletterWithRelations>>(queryKey);
const previousNewsletters = Array.isArray(queryData?.data)
? queryData.data
: Array.isArray(queryData)
? queryData
: [];
// For unarchive, we always update the status in place since we want to show unarchived newsletters
cacheManager.batchUpdateNewsletters(
ids.map((id) => ({
id,
updates: {
is_archived: false,
updated_at: new Date().toISOString(),
},
}))
);
return { previousNewsletters };
},
onError: (_err, ids, context) => {
if (context?.previousNewsletters) {
ids.forEach((id) => {
const newsletter = context.previousNewsletters!.find((n) => n.id === id);
if (newsletter) {
cacheManager.updateNewsletterInCache({
id,
updates: {
is_archived: newsletter.is_archived,
updated_at: newsletter.updated_at,
},
});
}
});
}
},
onSettled: (_data, _error, ids) => {
invalidateForOperation(queryClient, 'bulk-unarchive', ids);
// Dispatch event for unread count updates
window.dispatchEvent(new CustomEvent('newsletter:archived'));
},
});
// Delete newsletter mutation
const deleteNewsletterMutation = useMutation<boolean, Error, string, unknown>({
mutationFn: async (id: string) => {
return newsletterService.delete(id);
},
onSettled: (_data, _error, id) => {
invalidateForOperation(queryClient, 'delete', [id]);
},
});
// Bulk delete newsletters mutation
const bulkDeleteNewslettersMutation = useMutation<boolean, Error, string[], unknown>({
mutationFn: async (ids: string[]) => {
// Delete each newsletter individually since we don't have a bulk delete in the API yet
if (!ids || !Array.isArray(ids) || ids.length === 0) {
throw new Error('Invalid or empty newsletter IDs provided for bulk delete');
}
const promises = ids.map((id) => newsletterService.delete(id));
await Promise.all(promises);
return true;
},
onSettled: (_data, _error, ids) => {
if (ids && Array.isArray(ids)) {
invalidateForOperation(queryClient, 'bulk-delete', ids);
}
// Dispatch event for unread count updates
window.dispatchEvent(new CustomEvent('newsletter:deleted'));
},
});
// Toggle in-queue status mutation with improved optimistic updates
const toggleInQueueMutation = useMutation<
boolean,
Error,
string,
{
previousNewsletters: NewsletterWithRelations[];
wasInQueue: boolean;
rollbackFunctions: Array<() => void>;
previousQueueItems?: ReadingQueueItem[];
}
>({
mutationFn: async (id: string) => {
// Get current queue status from cache first, then API if needed
const queueItems =
getQueryData<ReadingQueueItem[]>(queryKeyFactory.queue.list(user?.id || '')) || [];
let isInQueue = queueItems.some((item) => item.newsletter_id === id);
// If cache is empty or unreliable, check API
if (queueItems.length === 0) {
try {
isInQueue = await readingQueueService.isInQueue(id);
} catch (error) {
log.warn(
'Failed to check queue status, proceeding with cache value',
{
action: 'check_queue_status',
metadata: { newsletterId: id },
},
error instanceof Error ? error : new Error(String(error))
);
}
}
// Perform the toggle operation
if (isInQueue) {
const queueItem = queueItems.find((item) => item.newsletter_id === id);
if (queueItem) {
await readingQueueService.remove(queueItem.id);
}
} else {
await readingQueueService.add(id);
}
return !isInQueue;
},
onMutate: async (id) => {
// Cancel any outgoing refetches to avoid race conditions
await cancelQueries({
predicate: (query) => {
const queryKey = query.queryKey as unknown[];
return (
queryKeyFactory.matchers.isNewsletterListKey(queryKey) ||
queryKeyFactory.matchers.isNewsletterDetailKey(queryKey, id) ||
queryKey[0] === 'reading-queue' ||
queryKey[0] === 'unreadCount'
);
},
});
const rollbackFunctions: Array<() => void> = [];
// Get current states for rollback
const previousNewsletters = getQueryData<NewsletterWithRelations[]>(queryKey) || [];
const newsletterArray = Array.isArray(previousNewsletters) ? previousNewsletters : [];
const queueItems =
getQueryData<ReadingQueueItem[]>(queryKeyFactory.queue.list(user?.id || '')) || [];
const wasInQueue = queueItems.some((item) => item.newsletter_id === id);
// Note: We don't need to update newsletter lists since queue status
// is managed separately through ReadingQueueItem table
// Apply optimistic updates to reading queue with better error handling
const queueQueryKey = queryKeyFactory.queue.list(user?.id || '');
try {
const result = await cacheManager.optimisticUpdateWithRollback<ReadingQueueItem[]>(
Array.from(queueQueryKey),
(data) => {
// Ensure we always have a valid array
const currentData = Array.isArray(data) ? data : [];
if (wasInQueue) {
// Remove from queue
return currentData.filter((item) => item.newsletter_id !== id);
} else {
// Add to queue (create a mock item for the UI)
const newsletter = newsletterArray.find((n) => n.id === id);
if (newsletter) {
const mockQueueItem: ReadingQueueItem = {
id: `temp-${id}`,
newsletter_id: id,
user_id: user?.id || '',
position: currentData.length + 1,
added_at: new Date().toISOString(),
newsletter,
};
return [...currentData, mockQueueItem];
}
}
return currentData;
}
);
if (result?.rollback) {
rollbackFunctions.push(result.rollback);
}
} catch (error) {
log.warn(
'Failed to apply optimistic update to queue',
{
action: 'optimistic_queue_update',
metadata: { newsletterId: id },
},
error instanceof Error ? error : new Error(String(error))
);
// Don't throw here - we want to continue with the mutation
}
return {
previousNewsletters: newsletterArray,
wasInQueue,
rollbackFunctions,
};
},
onError: (error, id, context) => {
log.error(
'Error toggling queue status',
{
action: 'toggle_queue_status',
metadata: { newsletterId: id },
},
error instanceof Error ? error : new Error(String(error))
);
// Execute all rollback functions
if (context?.rollbackFunctions) {
context.rollbackFunctions.forEach((rollback) => {
try {
rollback();
} catch (rollbackError) {
log.error(
'Error during rollback',
{
action: 'rollback_queue_toggle',
metadata: { newsletterId: id },
},
rollbackError instanceof Error ? rollbackError : new Error(String(rollbackError))
);
}
});
}
// Don't force refresh on error - let the UI handle retry
},
onSuccess: (_result, _id) => {
// Only invalidate the specific reading queue query
queryClient.invalidateQueries({
queryKey: queryKeyFactory.queue.list(user?.id || ''),
refetchType: 'none', // Don't refetch automatically
});
},
onSettled: (_data, _error, _id) => {
// No additional invalidation needed - handled in onSuccess
},
});
// Update newsletter tags mutation
const updateNewsletterTagsMutation = useMutation<
boolean,
Error,
{ id: string; tagIds: string[] },
PreviousNewslettersState
>({
mutationFn: async ({ id, tagIds }) => {
if (!user?.id) {
throw new Error('User authentication required');
}
// Get current newsletter to get current tags
const currentNewsletter = await newsletterService.getById(id);
if (!currentNewsletter) {
throw new Error('Newsletter not found');
}
const currentTagIds = currentNewsletter.tags?.map((tag) => tag.id) || [];
// Update newsletter tags using the tag utility - same as reading queue
await updateNewsletterTags(id, tagIds, currentTagIds, user.id);
return true;
},
onMutate: async ({ id }) => {
await cancelQueries({
predicate: (query) =>
queryKeyFactory.matchers.isNewsletterListKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterDetailKey(query.queryKey as unknown[], id),
});
const previousNewsletters = getQueryData<NewsletterWithRelations[]>(queryKey) || [];
// Optimistically update the newsletter with new tags
// Note: We don't have the full tag objects here, just IDs
// The actual tag objects will be fetched after the mutation succeeds
cacheManager.updateNewsletterInCache({
id,
updates: {
updated_at: new Date().toISOString(),
},
});
return { previousNewsletters };
},
onError: (_err, { id }, context) => {
// Revert optimistic updates if the mutation fails
if (context?.previousNewsletters) {
const newsletter = context.previousNewsletters.find((n) => n.id === id);
if (newsletter) {
cacheManager.updateNewsletterInCache({
id,
updates: {
updated_at: newsletter.updated_at,
},
});
}
}
},
onSettled: (_data, _error, { id }) => {
// Invalidate queries to refetch fresh data with updated tags
cacheManager.invalidateRelatedQueries([id], 'update-tags');
},
});
// Unarchive mutation (separate from toggle for specific use cases)
const unarchiveMutation = useMutation<boolean, Error, string, PreviousNewslettersState>({
mutationFn: async (id: string) => {
await newsletterService.update({ id, is_archived: false });
return true;
},
onMutate: async (id) => {
await cancelQueries({
predicate: (query) =>
queryKeyFactory.matchers.isNewsletterListKey(query.queryKey as unknown[]) ||
queryKeyFactory.matchers.isNewsletterDetailKey(query.queryKey as unknown[], id),
});
const previousNewsletters = getQueryData<NewsletterWithRelations[]>(queryKey) || [];
const newsletterArray = Array.isArray(previousNewsletters) ? previousNewsletters : [];
cacheManager.updateNewsletterInCache({
id,
updates: {
is_archived: false,
updated_at: new Date().toISOString(),
},
});
return { previousNewsletters: newsletterArray };
},
onError: (_err, id, context) => {
if (context?.previousNewsletters) {
const newsletter = context.previousNewsletters.find((n) => n.id === id);
if (newsletter) {
cacheManager.updateNewsletterInCache({
id,
updates: {
is_archived: newsletter.is_archived,
updated_at: newsletter.updated_at,
},
});
}
}
},
onSettled: (_data, _error, id) => {
cacheManager.invalidateRelatedQueries([id], 'unarchive');
},
});
// Memoized callback functions
const markAsRead = useCallback(
async (
id: string,
options?: MutateOptions<boolean, Error, string, PreviousNewslettersState>
) => {
return markAsReadMutation.mutateAsync(id, options);
},
[markAsReadMutation]
);
const markAsUnread = useCallback(
async (
id: string,
options?: MutateOptions<boolean, Error, string, PreviousNewslettersState>
) => {
return markAsUnreadMutation.mutateAsync(id, options);
},
[markAsUnreadMutation]
);
const bulkMarkAsRead = useCallback(
async (
ids: string[],
options?: MutateOptions<boolean, Error, string[], PreviousNewslettersState>
) => {
return bulkMarkAsReadMutation.mutateAsync(ids, options);
},
[bulkMarkAsReadMutation]
);
const bulkMarkAsUnread = useCallback(
async (
ids: string[],
options?: MutateOptions<boolean, Error, string[], PreviousNewslettersState>
) => {
return bulkMarkAsUnreadMutation.mutateAsync(ids, options);
},
[bulkMarkAsUnreadMutation]
);
const toggleLike = useCallback(
async (
id: string,
options?: MutateOptions<boolean, Error, string, PreviousNewslettersState>
) => {
return toggleLikeMutation.mutateAsync(id, options);
},
[toggleLikeMutation]
);
const toggleArchive = useCallback(
async (
id: string,
options?: MutateOptions<boolean, Error, string, PreviousNewslettersState>
) => {
return toggleArchiveMutation.mutateAsync(id, options);
},
[toggleArchiveMutation]
);
const bulkArchive = useCallback(
async (
ids: string[],
options?: MutateOptions<boolean, Error, string[], PreviousNewslettersState>
) => {
return bulkArchiveMutation.mutateAsync(ids, options);
},
[bulkArchiveMutation]
);
const bulkUnarchive = useCallback(
async (
ids: string[],
options?: MutateOptions<boolean, Error, string[], PreviousNewslettersState>
) => {
return bulkUnarchiveMutation.mutateAsync(ids, options);
},
[bulkUnarchiveMutation]
);
const updateNewsletterTagsCallback = useCallback(
async (
id: string,
tagIds: string[],
options?: MutateOptions<
boolean,
Error,
{ id: string; tagIds: string[] },
PreviousNewslettersState
>
) => {
await updateNewsletterTagsMutation.mutateAsync({ id, tagIds }, options);
},
[updateNewsletterTagsMutation]
);
return {
// Single newsletter operations
getNewsletter,
// Newsletter list and query
newsletters,
isLoadingNewsletters: isLoading,
isErrorNewsletters: !!errorNewsletters,
errorNewsletters,
refetchNewsletters,
// Read status mutations
markAsRead,
markAsUnread,
bulkMarkAsRead,
bulkMarkAsUnread,
isMarkingAsRead: markAsReadMutation.isPending,
errorMarkingAsRead: markAsReadMutation.error,
isMarkingAsUnread: markAsUnreadMutation.isPending,
errorMarkingAsUnread: markAsUnreadMutation.error,
isBulkMarkingAsRead: bulkMarkAsReadMutation.isPending,
errorBulkMarkingAsRead: bulkMarkAsReadMutation.error,
isBulkMarkingAsUnread: bulkMarkAsUnreadMutation.isPending,
errorBulkMarkingAsUnread: bulkMarkAsUnreadMutation.error,
// Like mutation
toggleLike,
isTogglingLike: toggleLikeMutation.isPending,
errorTogglingLike: toggleLikeMutation.error,
// Archive mutations
toggleArchive,
bulkArchive,
bulkUnarchive,
isArchiving: toggleArchiveMutation.isPending,
errorArchiving: toggleArchiveMutation.error,
isUnarchiving: unarchiveMutation.isPending,
errorUnarchiving: unarchiveMutation.error,
isBulkArchiving: bulkArchiveMutation.isPending,
errorBulkArchiving: bulkArchiveMutation.error,
isBulkUnarchiving: bulkUnarchiveMutation.isPending,
errorBulkUnarchiving: bulkUnarchiveMutation.error,
// Queue mutations
toggleInQueue: toggleInQueueMutation.mutateAsync,
isTogglingInQueue: toggleInQueueMutation.isPending,
errorTogglingInQueue: toggleInQueueMutation.error,
// Delete mutations
deleteNewsletter: deleteNewsletterMutation.mutateAsync,
isDeletingNewsletter: deleteNewsletterMutation.isPending,
errorDeletingNewsletter: deleteNewsletterMutation.error,
bulkDeleteNewsletters: bulkDeleteNewslettersMutation.mutateAsync,
isBulkDeletingNewsletters: bulkDeleteNewslettersMutation.isPending,
errorBulkDeletingNewsletters: bulkDeleteNewslettersMutation.error,
// Tag mutations
updateNewsletterTags: updateNewsletterTagsCallback,
isUpdatingTags: updateNewsletterTagsMutation.isPending,
errorUpdatingTags: updateNewsletterTagsMutation.error,
} as const;
};
|