Skip to content

Commit 729a276

Browse files
authored
fix(property-provider): memoize provider after the first evoke instead of immediately (#1471)
1 parent 0ca7227 commit 729a276

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

Diff for: packages/property-provider/src/memoize.spec.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@ describe("memoize", () => {
1515

1616
describe("static memoization", () => {
1717
it("should cache the resolved provider", async () => {
18-
expect.assertions(repeatTimes * 2);
18+
expect.assertions(repeatTimes * 2 + 1);
1919

2020
const memoized = memoize(provider);
21+
expect(provider).toHaveBeenCalledTimes(0);
2122
// eslint-disable-next-line @typescript-eslint/no-unused-vars
2223
for (const index in [...Array(repeatTimes).keys()]) {
2324
expect(await memoized()).toStrictEqual(mockReturn);
@@ -51,6 +52,7 @@ describe("memoize", () => {
5152
const isExpiredFalseTest = async (requiresRefresh?: any) => {
5253
isExpired.mockReturnValue(false);
5354
const memoized = memoize(provider, isExpired, requiresRefresh);
55+
expect(provider).toHaveBeenCalledTimes(0);
5456
// eslint-disable-next-line @typescript-eslint/no-unused-vars
5557
for (const index in [...Array(repeatTimes).keys()]) {
5658
expect(await memoized()).toEqual(mockReturn);

Diff for: packages/property-provider/src/memoize.ts

+13-3
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,26 @@ export const memoize: MemoizeOverload = <T>(
4343
isExpired?: (resolved: T) => boolean,
4444
requiresRefresh?: (resolved: T) => boolean
4545
): Provider<T> => {
46+
let result: any;
47+
let hasResult: boolean;
4648
if (isExpired === undefined) {
4749
// This is a static memoization; no need to incorporate refreshing
48-
const result = provider();
49-
return () => result;
50+
return () => {
51+
if (!hasResult) {
52+
result = provider();
53+
hasResult = true;
54+
}
55+
return result;
56+
};
5057
}
5158

52-
let result = provider();
5359
let isConstant = false;
5460

5561
return async () => {
62+
if (!hasResult) {
63+
result = provider();
64+
hasResult = true;
65+
}
5666
if (isConstant) {
5767
return result;
5868
}

0 commit comments

Comments
 (0)