Skip to content

Commit fe02c34

Browse files
atscottleonsenft
authored andcommitted
fix(core): avoid reloading a resource when params is unchanged
`ResourceImpl` wraps the result of `params()` in a `{request, reload}` object before feeding it to the state machine. That wrapper is allocated inside the computation of the `extRequest` linked signal, so when `params` is a plain function (rather than a `Signal`), any signal read inside `params()` is tracked directly as a producer of `extRequest`. Whenever that producer updates, `extRequest` re-runs its computation, allocates a new `{request, reload}` wrapper object that fails `Object.is`, and re-triggers the loader even when `params()` returned the exact same value. Wrap `request` in a `computed()` when `!isSignal(request)` so that `extRequest` tracks the memoized `computed` signal and only recomputes when `params()` actually changes (or when `request` is already a signal, tracks it directly without an extra `computed`). Also encapsulate caught errors via `encapsulateResourceError` directly in `extRequest` so non-Error thrown values (including `undefined`) are properly treated as errors. (cherry picked from commit 5c4b6a4)
1 parent b83a7be commit fe02c34

3 files changed

Lines changed: 139 additions & 3 deletions

File tree

‎packages/core/src/resource/resource.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -246,19 +246,33 @@ export class ResourceImpl<T, R> extends BaseWritableResource<T> implements Resou
246246

247247
this.transferState = injector.get(TransferState, undefined, {optional: true}) ?? undefined;
248248

249+
const paramsSignal = isSignal(request)
250+
? request
251+
: computed(
252+
() => {
253+
try {
254+
setInParamsFunction(true);
255+
return request(paramsContext);
256+
} finally {
257+
setInParamsFunction(false);
258+
}
259+
},
260+
ngDevMode ? createDebugNameObject(debugName, 'params') : undefined,
261+
);
262+
249263
this.extRequest = linkedSignal<WrappedRequest>(
250264
() => {
251265
try {
252266
setInParamsFunction(true);
253-
return {request: request(paramsContext), reload: 0};
267+
return {request: paramsSignal(), reload: 0};
254268
} catch (error) {
255269
rethrowFatalErrors(error);
256270
if (error === ResourceParamsStatus.IDLE) {
257271
return {status: 'idle', reload: 0};
258272
} else if (error === ResourceParamsStatus.LOADING) {
259273
return {status: 'loading', reload: 0};
260274
}
261-
return {error: error as Error, reload: 0};
275+
return {error: encapsulateResourceError(error), reload: 0};
262276
} finally {
263277
setInParamsFunction(false);
264278
}
@@ -279,7 +293,7 @@ export class ResourceImpl<T, R> extends BaseWritableResource<T> implements Resou
279293
if (error) {
280294
status = 'resolved';
281295
stream = signal(
282-
{error: encapsulateResourceError(error)},
296+
{error},
283297
ngDevMode ? createDebugNameObject(this.debugName, 'stream') : undefined,
284298
);
285299
} else if (!status) {

‎packages/core/test/resource/params_status_spec.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,4 +118,86 @@ describe('resource with ResourceParamsStatus', () => {
118118
expect(res.value()).toBe('foo');
119119
expect(loadCount).toBe(1);
120120
});
121+
122+
it('should propagate a different error thrown from params', async () => {
123+
const s = signal<string | Error>('foo');
124+
const res = await actAsync(() =>
125+
resource({
126+
params: throwStatusAndErrors(s),
127+
loader: async ({params}) => params as string,
128+
injector: TestBed.inject(Injector),
129+
}),
130+
);
131+
132+
await actAsync(() => s.set(new Error('first')));
133+
expect(res.status()).toBe('error');
134+
expect(res.error()).toEqual(new Error('first'));
135+
136+
await actAsync(() => s.set(new Error('second')));
137+
expect(res.status()).toBe('error');
138+
expect(res.error()).toEqual(new Error('second'));
139+
});
140+
141+
it('should keep the status when an unrelated signal re-runs params that throws the same status', async () => {
142+
const unrelated = signal(0);
143+
const s = signal<string | ResourceParamsStatus>(ResourceParamsStatus.LOADING);
144+
let paramsCount = 0;
145+
let loadCount = 0;
146+
const res = await actAsync(() =>
147+
resource({
148+
params: () => {
149+
paramsCount++;
150+
unrelated();
151+
return throwStatusAndErrors(s)();
152+
},
153+
loader: async ({params}) => {
154+
loadCount++;
155+
return params;
156+
},
157+
injector: TestBed.inject(Injector),
158+
}),
159+
);
160+
161+
expect(res.status()).toBe('loading');
162+
expect(paramsCount).toBe(1);
163+
164+
await actAsync(() => unrelated.set(1));
165+
166+
expect(paramsCount).toBe(2);
167+
expect(res.status()).toBe('loading');
168+
expect(loadCount).toBe(0);
169+
170+
await actAsync(() => s.set('foo'));
171+
expect(res.status()).toBe('resolved');
172+
expect(loadCount).toBe(1);
173+
});
174+
175+
it('should distinguish between returning undefined and throwing undefined in params', async () => {
176+
const throwIt = signal(false);
177+
let loads = 0;
178+
179+
const res = await actAsync(() =>
180+
resource({
181+
params: () => {
182+
if (throwIt()) {
183+
throw undefined;
184+
}
185+
return undefined;
186+
},
187+
loader: async () => {
188+
loads++;
189+
return 'loaded';
190+
},
191+
injector: TestBed.inject(Injector),
192+
}),
193+
);
194+
195+
expect(res.status()).toBe('idle');
196+
expect(loads).toBe(0);
197+
198+
await actAsync(() => throwIt.set(true));
199+
200+
expect(res.status()).toBe('error');
201+
expect(loads).toBe(0);
202+
});
121203
});

‎packages/core/test/resource/resource_spec.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1032,6 +1032,46 @@ describe('resource', () => {
10321032
expect(echoResource.error()).toEqual(undefined);
10331033
});
10341034

1035+
it('should not reload when a signal read in params changes but params returns the same value', async () => {
1036+
const routeParams = signal<{id: string; tab: string}>({id: '1', tab: 'overview'});
1037+
let loadCount = 0;
1038+
1039+
const userResource = resource({
1040+
params: () => routeParams().id,
1041+
loader: async ({params: id}) => {
1042+
loadCount++;
1043+
return `user-${id}-${loadCount}`;
1044+
},
1045+
injector: TestBed.inject(Injector),
1046+
});
1047+
1048+
await timeout();
1049+
expect(loadCount).toBe(1);
1050+
expect(userResource.value()).toBe('user-1-1');
1051+
1052+
// Updating `routeParams` with a new object that has the same `id` should not re-run the loader
1053+
routeParams.set({id: '1', tab: 'orders'});
1054+
await timeout();
1055+
expect(loadCount).toBe(1);
1056+
expect(userResource.value()).toBe('user-1-1');
1057+
1058+
// Even after a manual reload(), a subsequent signal update with the same `id` should not trigger another reload
1059+
userResource.reload();
1060+
await timeout();
1061+
expect(loadCount).toBe(2);
1062+
expect(userResource.value()).toBe('user-1-2');
1063+
1064+
routeParams.set({id: '1', tab: 'settings'});
1065+
await timeout();
1066+
expect(loadCount).toBe(2);
1067+
expect(userResource.value()).toBe('user-1-2');
1068+
1069+
routeParams.set({id: '2', tab: 'settings'});
1070+
await timeout();
1071+
expect(loadCount).toBe(3);
1072+
expect(userResource.value()).toBe('user-2-3');
1073+
});
1074+
10351075
describe('types', () => {
10361076
it('should narrow hasValue() when the value can be undefined', () => {
10371077
const result: ResourceRef<number | undefined> = resource({

0 commit comments

Comments
 (0)