Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/flat-eggs-reply.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"runed": patch
---

fix(resource): ensure data does not race
11 changes: 7 additions & 4 deletions packages/runed/src/lib/utilities/resource/resource.svelte.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { watch } from "$lib/utilities/watch/index.js";
import type { Getter } from "$lib/internal/types.js";
import { SvelteMap } from "svelte/reactivity";

/**
* Configuration options for the resource function
Expand Down Expand Up @@ -150,7 +151,8 @@ function runResource<

// Create state
let current = $state<Awaited<ReturnType<Fetcher>> | undefined>(initialValue);
let loading = $state(false);
const loadings = new SvelteMap<number, boolean>();
let fetchId = $state(0);
let error = $state<Error | undefined>(undefined);
let cleanupFns = $state<Array<() => void>>([]);

Expand All @@ -171,8 +173,9 @@ function runResource<
previousValue: Source | undefined | Array<Source | undefined>,
refetching: RefetchInfo | boolean = false
): Promise<Awaited<ReturnType<Fetcher>> | undefined> => {
const currentFetchId = ++fetchId;
try {
loading = true;
loadings.set(currentFetchId, true);
error = undefined;
runCleanup();

Expand All @@ -196,7 +199,7 @@ function runResource<
}
return undefined;
} finally {
loading = false;
loadings.delete(currentFetchId);
}
};

Expand Down Expand Up @@ -232,7 +235,7 @@ function runResource<
return current;
},
get loading() {
return loading;
return loadings.get(fetchId) ?? false;
},
get error() {
return error;
Expand Down
24 changes: 24 additions & 0 deletions packages/runed/src/lib/utilities/resource/resource.test.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,30 @@ describe("resource", () => {
expect(fetchedValues).toEqual([1, 2]);
expect(promiseResource.current).toBe(2);
});

testWithEffect("no data race in loading state", async () => {
let input = $state(1);

const dataRaceResource = resource(
() => input,
async (input, _, { signal }): Promise<number> => {
return new Promise((resolve, reject) => {
signal.onabort = () => {
reject(new Error("Aborted " + input));
};
sleep(300).then(() => resolve(input));
});
}
);
for (let i = 0; i < 5; i++) {
await sleep(50);
expect(dataRaceResource.loading).toBe(true);
input += 1;
}

await sleep(500);
expect(dataRaceResource.loading).toBe(false);
});
});

describe("error handling", () => {
Expand Down