Datasets:
Tasks:
Text Generation
Formats:
parquet
Sub-tasks:
language-modeling
Languages:
English
Size:
< 1K
License:
File size: 32,443 Bytes
5cba866 | 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 | diff --git a/packages/hooks/src/useRequest/__tests__/useCachePlugin.spec.tsx b/packages/hooks/src/useRequest/__tests__/useCachePlugin.spec.tsx
index 2ab551c7..3f8f5814 100644
--- a/packages/hooks/src/useRequest/__tests__/useCachePlugin.spec.tsx
+++ b/packages/hooks/src/useRequest/__tests__/useCachePlugin.spec.tsx
@@ -183,6 +183,562 @@ describe('useCachePlugin', () => {
expect(result.current.data).toBe('success');
});
+ const pageRequest = (calls: string[]) => (page: string, delay: number) => {
+ calls.push(page);
+ return new Promise<string>((resolve) => {
+ setTimeout(() => resolve(`data-${page}`), delay);
+ });
+ };
+
+ test('superseded response should still reach a custom setCache', async () => {
+ const store: Record<string, any> = {};
+ const { result } = setup(pageRequest([]), {
+ manual: true,
+ cacheKey: 'supersededSetCache',
+ setCache: (data) => {
+ store[data.params[0]] = data;
+ },
+ getCache: (params) => store[params[0]],
+ });
+
+ act(() => {
+ result.current.run('a', 300);
+ });
+ act(() => {
+ result.current.run('b', 600);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(400);
+ });
+ expect(store.a?.data).toBe('data-a');
+ expect(result.current.data).toBeUndefined();
+
+ await act(async () => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(store.b?.data).toBe('data-b');
+ expect(result.current.data).toBe('data-b');
+ });
+
+ test('late response should not replace newer data in the cache', async () => {
+ const request = pageRequest([]);
+ const hook1 = setup(request, { manual: true, cacheKey: 'lateResponse' });
+ const hook2 = setup(request, { manual: true, cacheKey: 'lateResponse' });
+
+ act(() => {
+ hook1.result.current.run('a', 800);
+ });
+ act(() => {
+ hook2.result.current.run('a', 800);
+ });
+ act(() => {
+ hook1.result.current.run('b', 200);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(900);
+ });
+
+ expect(hook1.result.current.data).toBe('data-b');
+ expect(hook1.result.current.params).toEqual(['b', 200]);
+ expect(hook2.result.current.data).toBe('data-a');
+ expect(setup(request, { manual: true, cacheKey: 'lateResponse' }).result.current.data).toBe(
+ 'data-b',
+ );
+ });
+
+ test('requests with different params should not share an in-flight request', async () => {
+ const calls: string[] = [];
+ const request = pageRequest(calls);
+ const hook1 = setup(request, { manual: true, cacheKey: 'differentParams' });
+ const hook2 = setup(request, { manual: true, cacheKey: 'differentParams' });
+
+ act(() => {
+ hook1.result.current.run('a', 500);
+ });
+ act(() => {
+ hook2.result.current.run('b', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(600);
+ });
+
+ expect(calls).toEqual(['a', 'b']);
+ expect(hook1.result.current.data).toBe('data-a');
+ expect(hook2.result.current.data).toBe('data-b');
+ });
+
+ test('settled request should not drop a newer in-flight request', async () => {
+ const calls: string[] = [];
+ const request = pageRequest(calls);
+ const hook1 = setup(request, { manual: true, cacheKey: 'newerInFlight' });
+
+ act(() => {
+ hook1.result.current.run('a', 50);
+ });
+ act(() => {
+ hook1.result.current.run('b', 500);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(100);
+ });
+
+ const hook2 = setup(request, { manual: true, cacheKey: 'newerInFlight' });
+ act(() => {
+ hook2.result.current.run('b', 500);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(500);
+ });
+
+ expect(calls).toEqual(['a', 'b']);
+ expect(hook2.result.current.data).toBe('data-b');
+ });
+
+ test('responses arriving in reverse order should all reach a per-params store', async () => {
+ const store: Record<string, any> = {};
+ const { result } = setup(pageRequest([]), {
+ manual: true,
+ cacheKey: 'reverseOrderStore',
+ setCache: (data) => {
+ store[data.params[0]] = data;
+ },
+ getCache: (params) => store[params[0]],
+ });
+
+ act(() => {
+ result.current.run('a', 900);
+ });
+ act(() => {
+ result.current.run('b', 600);
+ });
+ act(() => {
+ result.current.run('c', 300);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ expect(Object.keys(store).sort()).toEqual(['a', 'b', 'c']);
+ expect(result.current.data).toBe('data-c');
+ });
+
+ test('responses arriving in reverse order should leave a single-entry store on the newest', async () => {
+ let entry: any;
+ const { result } = setup(pageRequest([]), {
+ manual: true,
+ cacheKey: 'reverseOrderSingle',
+ setCache: (data) => {
+ entry = data;
+ },
+ getCache: () => entry,
+ });
+
+ act(() => {
+ result.current.run('a', 900);
+ });
+ act(() => {
+ result.current.run('b', 600);
+ });
+ act(() => {
+ result.current.run('c', 300);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ expect(entry?.data).toBe('data-c');
+ });
+
+ test('a late page another instance still shows should reach a per-params store', async () => {
+ const store: Record<string, any> = {};
+ const request = pageRequest([]);
+ const options = {
+ manual: true,
+ cacheKey: 'lateShownPage',
+ setCache: (data: any) => {
+ store[data.params[0]] = data;
+ },
+ getCache: (params: any[]) => store[params[0]],
+ };
+ const hook1 = setup(request, options);
+ const hook2 = setup(request, options);
+
+ act(() => {
+ hook1.result.current.run('a', 700);
+ });
+ act(() => {
+ hook2.result.current.run('a', 700);
+ });
+ act(() => {
+ hook1.result.current.run('b', 200);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(800);
+ });
+
+ expect(hook2.result.current.data).toBe('data-a');
+ expect(store.a?.data).toBe('data-a');
+ expect(store.b?.data).toBe('data-b');
+ });
+
+ test('mutate should reach instances with the same params only', async () => {
+ const request = pageRequest([]);
+ const options = { manual: true, cacheKey: 'mutateSameParams' };
+ const hook1 = setup(request, options);
+ const hook2 = setup(request, options);
+ const hook3 = setup(request, options);
+
+ act(() => {
+ hook1.result.current.run('a', 100);
+ });
+ act(() => {
+ hook2.result.current.run('a', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(150);
+ });
+ act(() => {
+ hook3.result.current.run('b', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(150);
+ });
+ act(() => {
+ hook1.result.current.mutate('data-a-edited');
+ });
+
+ expect(hook2.result.current.data).toBe('data-a-edited');
+ expect(hook3.result.current.data).toBe('data-b');
+ });
+
+ test('superseded response arriving last should still reach a per-params store', async () => {
+ const store: Record<string, any> = {};
+ const { result } = setup(pageRequest([]), {
+ manual: true,
+ cacheKey: 'supersededLast',
+ setCache: (data) => {
+ store[data.params[0]] = data;
+ },
+ getCache: (params) => store[params[0]],
+ });
+
+ act(() => {
+ result.current.run('a', 300);
+ });
+ act(() => {
+ result.current.run('b', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(400);
+ });
+
+ expect(result.current.data).toBe('data-b');
+ expect(store.a?.data).toBe('data-a');
+ });
+
+ test('a single-entry store should hold the params requested last across instances', async () => {
+ let entry: any;
+ const request = pageRequest([]);
+ const options = {
+ manual: true,
+ cacheKey: 'singleEntryInstances',
+ setCache: (data: any) => {
+ entry = data;
+ },
+ getCache: () => entry,
+ };
+ const hook1 = setup(request, options);
+ const hook2 = setup(request, options);
+
+ act(() => {
+ hook1.result.current.run('a', 300);
+ });
+ act(() => {
+ hook2.result.current.run('b', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(400);
+ });
+
+ expect(hook1.result.current.data).toBe('data-a');
+ expect(entry?.data).toBe('data-b');
+ });
+
+ test('the built-in cache should hold the params requested last across instances', async () => {
+ const request = pageRequest([]);
+ const options = { manual: true, cacheKey: 'builtInInstances' };
+ const hook1 = setup(request, options);
+ const hook2 = setup(request, options);
+
+ act(() => {
+ hook1.result.current.run('a', 300);
+ });
+ act(() => {
+ hook2.result.current.run('b', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(400);
+ });
+
+ expect(hook1.result.current.data).toBe('data-a');
+ expect(setup(request, options).result.current.data).toBe('data-b');
+ });
+
+ test('an instance without params should follow the newest response', async () => {
+ const request = pageRequest([]);
+ const options = { manual: true, cacheKey: 'noParamsInstance' };
+ const hook1 = setup(request, options);
+ const hook2 = setup(request, options);
+
+ act(() => {
+ hook1.result.current.run('a', 500);
+ });
+ act(() => {
+ hook2.result.current.run('a', 500);
+ });
+ act(() => {
+ hook1.result.current.run('b', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(50);
+ });
+ const hook3 = setup(request, options);
+ await act(async () => {
+ vi.advanceTimersByTime(550);
+ });
+
+ expect(hook2.result.current.data).toBe('data-a');
+ expect(hook3.result.current.data).toBe('data-b');
+ });
+
+ test('an instance requesting other params should show its own response', async () => {
+ const request = pageRequest([]);
+ const options = { manual: true, cacheKey: 'otherParamsLater' };
+ const hook1 = setup(request, options);
+ const hook2 = setup(request, options);
+
+ act(() => {
+ hook1.result.current.run('b', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(150);
+ });
+ act(() => {
+ hook2.result.current.run('a', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(150);
+ });
+
+ expect(hook2.result.current.data).toBe('data-a');
+ expect(hook1.result.current.data).toBe('data-b');
+ });
+
+ test('an instance sharing a request should take a newer response for the same params', async () => {
+ const delays = [400, 100];
+ let count = 0;
+ const request = (page: string) => {
+ count += 1;
+ const n = count;
+ return new Promise<string>((resolve) => {
+ setTimeout(() => resolve(`data-${page}-${n}`), delays.shift());
+ });
+ };
+ const options = { manual: true, cacheKey: 'sharedThenRefreshed' };
+ const hook1 = setup(request, options);
+ const hook2 = setup(request, options);
+
+ act(() => {
+ hook1.result.current.run('a');
+ });
+ act(() => {
+ hook2.result.current.run('a');
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(50);
+ });
+ act(() => {
+ hook1.result.current.refresh();
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(500);
+ });
+
+ expect(hook1.result.current.data).toBe('data-a-2');
+ expect(hook2.result.current.data).toBe('data-a-2');
+ });
+
+ test('an instance mounted with the params in flight should share the request', async () => {
+ const calls: string[] = [];
+ const request = pageRequest(calls);
+ const hook1 = setup(request, { manual: true, cacheKey: 'mountedMidLoad' });
+
+ act(() => {
+ hook1.result.current.run('a', 100);
+ hook1.result.current.run('b', 1000);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(151);
+ });
+ const hook2 = setup(request, { cacheKey: 'mountedMidLoad', defaultParams: ['b', 1000] });
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ expect(calls).toEqual(['a', 'b']);
+ expect(hook2.result.current.data).toBe('data-b');
+ });
+
+ test('the built-in cache should keep every page loaded under a key', async () => {
+ const request = pageRequest([]);
+ const options = { manual: true, cacheKey: 'keepEveryPage' };
+ const hook1 = setup(request, options);
+
+ act(() => {
+ hook1.result.current.run('a', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(100);
+ });
+ act(() => {
+ hook1.result.current.run('b', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(100);
+ });
+
+ const hook2 = setup(request, options);
+ expect(hook2.result.current.data).toBe('data-b');
+ act(() => {
+ hook2.result.current.run('a', 100);
+ });
+ expect(hook2.result.current.data).toBe('data-a');
+ });
+
+ test('a fresh page should be served again without a request', async () => {
+ const calls: string[] = [];
+ const request = pageRequest(calls);
+ const { result } = setup(request, {
+ manual: true,
+ cacheKey: 'freshPageAgain',
+ staleTime: 10000,
+ });
+
+ act(() => {
+ result.current.run('a', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(100);
+ });
+ act(() => {
+ result.current.run('b', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(100);
+ });
+ act(() => {
+ result.current.run('a', 100);
+ });
+
+ expect(result.current.data).toBe('data-a');
+ expect(result.current.loading).toBe(false);
+ expect(calls).toEqual(['a', 'b']);
+ });
+
+ test('a superseded response should be kept in the built-in cache for its own params', async () => {
+ const request = pageRequest([]);
+ const options = { manual: true, cacheKey: 'supersededBuiltIn' };
+ const hook1 = setup(request, options);
+
+ act(() => {
+ hook1.result.current.run('a', 300);
+ });
+ act(() => {
+ hook1.result.current.run('b', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(400);
+ });
+
+ const hook2 = setup(request, options);
+ expect(hook2.result.current.data).toBe('data-b');
+ act(() => {
+ hook2.result.current.run('a', 300);
+ });
+ expect(hook2.result.current.data).toBe('data-a');
+ });
+
+ test('a superseded response should be cached under the cacheKey it was requested with', async () => {
+ const request = pageRequest([]);
+ const hook = renderHook(
+ ({ page }) =>
+ useRequest(() => request(page, page === 'a' ? 300 : 100), {
+ cacheKey: `keyPerPage-${page}`,
+ refreshDeps: [page],
+ }),
+ { initialProps: { page: 'a' } },
+ );
+ await act(async () => {
+ vi.advanceTimersByTime(50);
+ });
+ hook.rerender({ page: 'b' });
+ await act(async () => {
+ vi.advanceTimersByTime(400);
+ });
+ expect(hook.result.current.data).toBe('data-b');
+
+ hook.rerender({ page: 'a' });
+ expect(hook.result.current.data).toBe('data-a');
+ });
+
+ test('an instance should follow its current cacheKey, not the one it mounted with', async () => {
+ const request = pageRequest([]);
+ const useList = ({ page }: { page: string }) =>
+ useRequest(() => request(page, page === 'a' ? 300 : 500), {
+ cacheKey: `followKey-${page}`,
+ refreshDeps: [page],
+ });
+ const hook1 = renderHook(useList, { initialProps: { page: 'a' } });
+ const hook2 = renderHook(useList, { initialProps: { page: 'a' } });
+
+ await act(async () => {
+ vi.advanceTimersByTime(50);
+ });
+ hook2.rerender({ page: 'b' });
+ await act(async () => {
+ vi.advanceTimersByTime(300);
+ });
+
+ expect(hook1.result.current.data).toBe('data-a');
+ expect(hook2.result.current.data).toBeUndefined();
+ });
+
+ test('cached data of other params should not be returned as fresh', async () => {
+ const calls: string[] = [];
+ const request = pageRequest(calls);
+ const options = { manual: true, cacheKey: 'otherParamsFresh', staleTime: 10000 };
+ const hook1 = setup(request, options);
+
+ act(() => {
+ hook1.result.current.run('a', 100);
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(100);
+ });
+
+ act(() => {
+ hook1.result.current.run('b', 100);
+ });
+ expect(calls).toEqual(['a', 'b']);
+ expect(hook1.result.current.loading).toBe(true);
+ await act(async () => {
+ vi.advanceTimersByTime(100);
+ });
+
+ expect(calls).toEqual(['a', 'b']);
+ expect(hook1.result.current.data).toBe('data-b');
+ });
+
//github.com/alibaba/hooks/issues/1859
test('error should reset with activeKey', async () => {
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
diff --git a/packages/hooks/src/useRequest/src/Fetch.ts b/packages/hooks/src/useRequest/src/Fetch.ts
index 2039b2c9..3b44e1ff 100644
--- a/packages/hooks/src/useRequest/src/Fetch.ts
+++ b/packages/hooks/src/useRequest/src/Fetch.ts
@@ -82,6 +82,7 @@ export default class Fetch<TData, TParams extends any[]> {
const res = await servicePromise;
if (currentCount !== this.count) {
+ this.runPluginHandler('onSuperseded', res, params);
throw new CancelledError();
}
diff --git a/packages/hooks/src/useRequest/src/plugins/useCachePlugin.ts b/packages/hooks/src/useRequest/src/plugins/useCachePlugin.ts
index ba6aa886..891ea026 100644
--- a/packages/hooks/src/useRequest/src/plugins/useCachePlugin.ts
+++ b/packages/hooks/src/useRequest/src/plugins/useCachePlugin.ts
@@ -1,12 +1,41 @@
import { useRef } from 'react';
import useCreation from '../../../useCreation';
import useUnmount from '../../../useUnmount';
+import { depsEqual } from '../../../utils/depsEqual';
import type { Plugin } from '../types';
import { setCache, getCache } from '../utils/cache';
import type { CachedData } from '../utils/cache';
import { setCachePromise, getCachePromise } from '../utils/cachePromise';
import { trigger, subscribe } from '../utils/cacheSubscribe';
+// Start order of requests across all instances. A write is dropped when a request
+// that started later has already written the same cacheKey.
+let requestOrder = 0;
+const orderOfPromise = new WeakMap<Promise<any>, number>();
+const orderOfParams = new WeakMap<any[], number>();
+const lastWrittenOrder = new Map<string, number>();
+// Start order of the request behind each entry written, per cacheKey and params.
+const writtenOrders = new Map<string, { params: any[]; order: number }[]>();
+
+const orderWrittenFor = (key: string, params: any[]) =>
+ writtenOrders.get(key)?.find((entry) => depsEqual(entry.params, params))?.order;
+
+const recordWritten = (key: string, params: any[], order: number) => {
+ const entries = writtenOrders.get(key) ?? [];
+ const entry = entries.find((e) => depsEqual(e.params, params));
+ if (entry) {
+ entry.order = Math.max(entry.order, order);
+ } else {
+ entries.push({ params, order });
+ }
+ writtenOrders.set(key, entries);
+};
+const paramsOfPromise = new WeakMap<Promise<any>, any[]>();
+// The cacheKey a request was made under; the option may have changed by the time it answers.
+const keyOfParams = new WeakMap<any[], string>();
+// Params of the latest request under each key: the page a new reader starts from.
+const latestParamsOfKey = new Map<string, any[]>();
+
const useCachePlugin: Plugin<any, any[]> = (
fetchInstance,
{
@@ -18,23 +47,61 @@ const useCachePlugin: Plugin<any, any[]> = (
},
) => {
const unSubscribeRef = useRef<() => void>(undefined);
+ const subscribedKeyRef = useRef<string | undefined>(undefined);
const currentPromiseRef = useRef<Promise<any>>(undefined);
- const _setCache = (key: string, cachedData: CachedData) => {
+ // Without params: the page of the latest request, or nothing while it is still loading.
+ // With params: that page only.
+ const _getCache = (key: string, params?: any[]) => {
+ if (customGetCache) {
+ return customGetCache(params ?? []);
+ }
+ const latestParams = latestParamsOfKey.get(key);
+ return getCache(key, params ?? latestParams);
+ };
+
+ // The store is asked what it holds for these params: a single-slot store answers with
+ // whatever page it has, a per-page store only for this page. A write is dropped when
+ // that entry came from a request that started later.
+ const _setCache = (key: string, cachedData: CachedData, order: number, notify = true) => {
+ const held = _getCache(key, cachedData.params);
+ const heldOrder = held && 'data' in held ? orderWrittenFor(key, held.params) : undefined;
+ if (heldOrder !== undefined && order < heldOrder) {
+ return;
+ }
+ recordWritten(key, cachedData.params, order);
+ const isLatest = order >= (lastWrittenOrder.get(key) ?? 0);
+ if (isLatest) {
+ lastWrittenOrder.set(key, order);
+ }
if (customSetCache) {
customSetCache(cachedData);
} else {
- setCache(key, cacheTime, cachedData);
+ setCache(key, cacheTime, cachedData, isLatest);
+ }
+ if (notify && isLatest) {
+ trigger(key, cachedData.data, cachedData.params);
}
- trigger(key, cachedData.data);
};
- const _getCache = (key: string, params: any[] = []) => {
- if (customGetCache) {
- return customGetCache(params);
- }
- return getCache(key);
+ // A component that has params of its own only takes data requested with the same params.
+ const _subscribe = (key: string) => {
+ unSubscribeRef.current?.();
+ subscribedKeyRef.current = key;
+ unSubscribeRef.current = subscribe(key, (data, params) => {
+ const ownParams = fetchInstance.state.params;
+ if (params && ownParams && !depsEqual(params, ownParams)) {
+ return;
+ }
+ fetchInstance.setState({ data });
+ });
+ };
+
+ const _unsubscribe = () => {
+ unSubscribeRef.current?.();
+ unSubscribeRef.current = undefined;
+ subscribedKeyRef.current = undefined;
};
useCreation(() => {
@@ -53,13 +120,20 @@ const useCachePlugin: Plugin<any, any[]> = (
}
// subscribe same cachekey update, trigger update
- unSubscribeRef.current = subscribe(cacheKey, (data) => {
- fetchInstance.setState({ data });
- });
+ _subscribe(cacheKey);
}, []);
+ // Follow the key currently rendered, so a change of cacheKey drops the old key's updates.
+ if (cacheKey !== subscribedKeyRef.current) {
+ if (cacheKey) {
+ _subscribe(cacheKey);
+ } else {
+ _unsubscribe();
+ }
+ }
+
useUnmount(() => {
- unSubscribeRef.current?.();
+ _unsubscribe();
});
if (!cacheKey) {
@@ -93,44 +167,86 @@ const useCachePlugin: Plugin<any, any[]> = (
onRequest: (service, args) => {
let servicePromise = getCachePromise(cacheKey);
- // If has servicePromise, and is not trigger by self, then use it
- if (servicePromise && servicePromise !== currentPromiseRef.current) {
- return { servicePromise };
+ // If has servicePromise for the same params, and is not trigger by self, then use it
+ if (
+ servicePromise &&
+ servicePromise !== currentPromiseRef.current &&
+ depsEqual(paramsOfPromise.get(servicePromise), args)
+ ) {
+ // A shared request is as old as the one that started it.
+ const sharedOrder = orderOfPromise.get(servicePromise) ?? ++requestOrder;
+ orderOfParams.set(args, sharedOrder);
+ keyOfParams.set(args, cacheKey);
+ latestParamsOfKey.set(cacheKey, args);
+ // A newer request for the same params may have written before this one settles.
+ return {
+ servicePromise: servicePromise.then((data) => {
+ const held = _getCache(cacheKey, args);
+ const heldOrder =
+ held && 'data' in held && depsEqual(held.params, args)
+ ? orderWrittenFor(cacheKey, args)
+ : undefined;
+ return heldOrder !== undefined && heldOrder > sharedOrder ? held.data : data;
+ }),
+ };
}
servicePromise = service(...args);
+ const order = ++requestOrder;
+ orderOfPromise.set(servicePromise, order);
+ paramsOfPromise.set(servicePromise, args);
+ orderOfParams.set(args, order);
+ keyOfParams.set(args, cacheKey);
+ latestParamsOfKey.set(cacheKey, args);
currentPromiseRef.current = servicePromise;
setCachePromise(cacheKey, servicePromise);
return { servicePromise };
},
- onSuccess: (data, params) => {
- if (cacheKey) {
- // cancel subscribe, avoid trgger self
- unSubscribeRef.current?.();
- _setCache(cacheKey, {
+ onSuperseded: (data, params) => {
+ // Stored for later reads, but never pushed to components waiting on a newer request.
+ _setCache(
+ keyOfParams.get(params) ?? cacheKey,
+ {
data,
params,
time: Date.now(),
- });
+ },
+ orderOfParams.get(params) ?? 0,
+ false,
+ );
+ },
+ onSuccess: (data, params) => {
+ if (cacheKey) {
+ // cancel subscribe, avoid trgger self
+ _unsubscribe();
+ _setCache(
+ keyOfParams.get(params) ?? cacheKey,
+ {
+ data,
+ params,
+ time: Date.now(),
+ },
+ orderOfParams.get(params) ?? ++requestOrder,
+ );
// resubscribe
- unSubscribeRef.current = subscribe(cacheKey, (d) => {
- fetchInstance.setState({ data: d });
- });
+ _subscribe(cacheKey);
}
},
onMutate: (data) => {
if (cacheKey) {
// cancel subscribe, avoid trigger self
- unSubscribeRef.current?.();
- _setCache(cacheKey, {
- data,
- params: fetchInstance.state.params,
- time: Date.now(),
- });
+ _unsubscribe();
+ _setCache(
+ cacheKey,
+ {
+ data,
+ params: fetchInstance.state.params,
+ time: Date.now(),
+ },
+ ++requestOrder,
+ );
// resubscribe
- unSubscribeRef.current = subscribe(cacheKey, (d) => {
- fetchInstance.setState({ data: d });
- });
+ _subscribe(cacheKey);
}
},
};
diff --git a/packages/hooks/src/useRequest/src/types.ts b/packages/hooks/src/useRequest/src/types.ts
index 2e0eabd3..4de36d0f 100644
--- a/packages/hooks/src/useRequest/src/types.ts
+++ b/packages/hooks/src/useRequest/src/types.ts
@@ -30,6 +30,8 @@ export interface PluginReturn<TData, TParams extends any[]> {
};
onSuccess?: (data: TData, params: TParams) => void;
+ /** A request resolved after a newer call or `cancel()` made its result unused. */
+ onSuperseded?: (data: TData, params: TParams) => void;
onError?: (e: Error, params: TParams) => void;
onFinally?: (params: TParams, data?: TData, e?: Error) => void;
onCancel?: () => void;
diff --git a/packages/hooks/src/useRequest/src/utils/cache.ts b/packages/hooks/src/useRequest/src/utils/cache.ts
index d16f9604..e023f372 100644
--- a/packages/hooks/src/useRequest/src/utils/cache.ts
+++ b/packages/hooks/src/useRequest/src/utils/cache.ts
@@ -1,3 +1,5 @@
+import { depsEqual } from '../../../utils/depsEqual';
+
type Timer = ReturnType<typeof setTimeout>;
type CachedKey = string | number;
@@ -10,7 +12,8 @@ interface RecordData extends CachedData {
timer: Timer | undefined;
}
-const cache = new Map<CachedKey, RecordData>();
+// One record per params under each key; the first record is the newest page.
+const cache = new Map<CachedKey, RecordData[]>();
const clearTimer = (cachedData?: RecordData) => {
if (cachedData?.timer) {
@@ -18,40 +21,74 @@ const clearTimer = (cachedData?: RecordData) => {
}
};
-const setCache = (key: CachedKey, cacheTime: number, cachedData: CachedData) => {
- const currentCache = cache.get(key);
- clearTimer(currentCache);
+const removeRecord = (key: CachedKey, record: RecordData) => {
+ const records = cache.get(key);
+ if (!records) {
+ return;
+ }
+ const index = records.indexOf(record);
+ if (index > -1) {
+ records.splice(index, 1);
+ }
+ if (!records.length) {
+ cache.delete(key);
+ }
+};
- let timer: Timer | undefined = undefined;
+// `latest` false keeps the record out of the first slot: an older page that answers
+// late is kept for its own params without becoming the page a new reader starts from.
+const setCache = (
+ key: CachedKey,
+ cacheTime: number,
+ cachedData: CachedData,
+ latest: boolean = true,
+) => {
+ const records = cache.get(key) ?? [];
+ const index = records.findIndex((record) => depsEqual(record.params, cachedData.params));
+ if (index > -1) {
+ clearTimer(records[index]);
+ records.splice(index, 1);
+ }
+
+ const record: RecordData = { ...cachedData, timer: undefined };
if (cacheTime > -1) {
// if cache out, clear it
- timer = setTimeout(() => {
- cache.delete(key);
+ record.timer = setTimeout(() => {
+ removeRecord(key, record);
}, cacheTime);
}
- cache.set(key, {
- ...cachedData,
- timer,
- });
+ if (latest || index === -1) {
+ records.splice(latest ? 0 : records.length, 0, record);
+ } else {
+ records.splice(index, 0, record);
+ }
+ cache.set(key, records);
};
-const getCache = (key: CachedKey) => {
- return cache.get(key);
+// Without params, the newest record of the key; with params, the record for those params.
+const getCache = (key: CachedKey, params?: any[]) => {
+ const records = cache.get(key);
+ if (!records?.length) {
+ return undefined;
+ }
+ if (!params) {
+ return records[0];
+ }
+ return records.find((record) => depsEqual(record.params, params));
};
const clearCache = (key?: string | string[]) => {
if (key) {
const cacheKeys = Array.isArray(key) ? key : [key];
cacheKeys.forEach((cacheKey) => {
- const currentCache = cache.get(cacheKey);
- clearTimer(currentCache);
+ cache.get(cacheKey)?.forEach(clearTimer);
cache.delete(cacheKey);
});
} else {
- for (const currentCache of cache.values()) {
- clearTimer(currentCache);
+ for (const records of cache.values()) {
+ records.forEach(clearTimer);
}
cache.clear();
}
diff --git a/packages/hooks/src/useRequest/src/utils/cachePromise.ts b/packages/hooks/src/useRequest/src/utils/cachePromise.ts
index e654aa44..a5055324 100644
--- a/packages/hooks/src/useRequest/src/utils/cachePromise.ts
+++ b/packages/hooks/src/useRequest/src/utils/cachePromise.ts
@@ -10,15 +10,20 @@ const setCachePromise = (cacheKey: CachedKey, promise: Promise<any>) => {
// Because the promise.finally will change the reference of the promise
cachePromise.set(cacheKey, promise);
+ // A newer request may have taken the key since; only remove our own entry.
+ const remove = () => {
+ if (cachePromise.get(cacheKey) === promise) {
+ cachePromise.delete(cacheKey);
+ }
+ };
+
// no use promise.finally for compatibility
promise
.then((res) => {
- cachePromise.delete(cacheKey);
+ remove();
return res;
})
- .catch(() => {
- cachePromise.delete(cacheKey);
- });
+ .catch(remove);
};
export { getCachePromise, setCachePromise };
diff --git a/packages/hooks/src/useRequest/src/utils/cacheSubscribe.ts b/packages/hooks/src/useRequest/src/utils/cacheSubscribe.ts
index 84f690d7..05190c39 100644
--- a/packages/hooks/src/useRequest/src/utils/cacheSubscribe.ts
+++ b/packages/hooks/src/useRequest/src/utils/cacheSubscribe.ts
@@ -1,9 +1,9 @@
-type Listener = (data: any) => void;
+type Listener = (data: any, params?: any[]) => void;
const listeners: Record<string, Listener[]> = {};
-const trigger = (key: string, data: any) => {
+const trigger = (key: string, data: any, params?: any[]) => {
if (listeners[key]) {
- listeners[key].forEach((item) => item(data));
+ listeners[key].forEach((item) => item(data, params));
}
};
|