Skip to content

Commit 0e42fb1

Browse files
authored
Merge pull request #2250 from cardstack/improve-resource-loading
do not run load card if not needed
2 parents 1e9a06f + 16e547a commit 0e42fb1

File tree

1 file changed

+39
-17
lines changed

1 file changed

+39
-17
lines changed

packages/host/app/resources/card-resource.ts

+39-17
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,13 @@ export class CardResource extends Resource<Args> {
4646
// and just being symmetric with the card error as well
4747
@tracked private _error: CardError | undefined;
4848
@tracked private _isLoaded = false;
49-
@tracked private _loaded: Promise<void> | undefined;
49+
private _loading:
50+
| {
51+
promise: Promise<void>;
52+
urlOrDoc: string | LooseSingleCardDocument | undefined;
53+
relativeTo: URL | undefined;
54+
}
55+
| undefined;
5056
declare private store: StoreService;
5157
declare private cardService: CardService;
5258
#url: string | undefined;
@@ -74,8 +80,15 @@ export class CardResource extends Resource<Args> {
7480
this.#isLive = isLive;
7581
this.#isAutoSave = isAutoSave;
7682

77-
if (urlOrDoc) {
78-
this._loaded = this.load.perform(urlOrDoc, relativeTo);
83+
if (
84+
urlOrDoc !== this._loading?.urlOrDoc ||
85+
relativeTo !== this._loading?.relativeTo
86+
) {
87+
this._loading = {
88+
promise: this.load.perform(urlOrDoc, relativeTo),
89+
urlOrDoc,
90+
relativeTo,
91+
};
7992
}
8093

8194
registerDestructor(this, () => {
@@ -114,23 +127,32 @@ export class CardResource extends Resource<Args> {
114127
// This is deprecated. consumers of this resource need to be reactive such
115128
// that they can deal with a resource that doesn't have a card yet.
116129
get loaded() {
117-
return this._loaded;
130+
return this._loading?.promise;
118131
}
119132

120133
private load = restartableTask(
121-
async (urlOrDoc: string | LooseSingleCardDocument, relativeTo?: URL) => {
122-
this.#api = await this.cardService.getAPI();
123-
let { url, card, error } = await this.store.createSubscriber({
124-
resource: this,
125-
urlOrDoc,
126-
relativeTo,
127-
setCard: (card) => {
128-
if (card !== this.card) {
129-
this._card = card;
130-
}
131-
},
132-
setCardError: (error) => (this._error = error),
133-
});
134+
async (
135+
urlOrDoc: string | LooseSingleCardDocument | undefined,
136+
relativeTo?: URL,
137+
) => {
138+
let url: string | undefined;
139+
let card: CardDef | undefined;
140+
let error: CardError | undefined;
141+
142+
if (urlOrDoc) {
143+
this.#api = await this.cardService.getAPI();
144+
({ url, card, error } = await this.store.createSubscriber({
145+
resource: this,
146+
urlOrDoc,
147+
relativeTo,
148+
setCard: (card) => {
149+
if (card !== this.card) {
150+
this._card = card;
151+
}
152+
},
153+
setCardError: (error) => (this._error = error),
154+
}));
155+
}
134156
this.#url = url;
135157
this._card = card;
136158
this._error = error;

0 commit comments

Comments
 (0)