diff --git a/packages/store/__tests__/index.test.ts b/packages/store/__tests__/index.test.ts index ec3a774..f77df6c 100644 --- a/packages/store/__tests__/index.test.ts +++ b/packages/store/__tests__/index.test.ts @@ -42,7 +42,7 @@ describe("Store utilities", () => { describe("synced", () => { it("should sync with localStorage", async () => { - const store = synced({ + const store = await synced({ key: "testKey", storage: localStorageProvider, defaultValue: "default", @@ -63,7 +63,7 @@ describe("Store utilities", () => { it("should load existing value from localStorage", async () => { localStorage.setItem("testKey", JSON.stringify("existing")) - const store = synced({ + const store = await synced({ key: "testKey", storage: localStorageProvider, defaultValue: "default", @@ -78,7 +78,7 @@ describe("Store utilities", () => { describe("getter", () => { it("should return current store value", async () => { - const store = synced({ + const store = await synced({ key: "test", storage: localStorageProvider, defaultValue: "initial", @@ -98,7 +98,7 @@ describe("Store utilities", () => { describe("withGetter", () => { it("should add getter to writable store", async () => { const store = withGetter( - synced({ + await synced({ key: "test", storage: localStorageProvider, defaultValue: "initial", @@ -117,7 +117,7 @@ describe("Store utilities", () => { describe("throttled", () => { it("should throttle updates", async () => { const mockFn = vi.fn() - const store = synced({ + const store = await synced({ key: "test", storage: localStorageProvider, defaultValue: 0, diff --git a/packages/store/src/synced.ts b/packages/store/src/synced.ts index 77c6819..23cd902 100644 --- a/packages/store/src/synced.ts +++ b/packages/store/src/synced.ts @@ -17,12 +17,14 @@ export interface SyncConfig { storage: StorageProvider } -export const sync = ({key, store, storage}: SyncConfig) => { - storage.get(key).then((value: T | undefined) => { - if (value !== undefined) { - store.set(value) - } - }) +export type Synced = Writable & {ready: Promise} + +export const sync = async ({key, store, storage}: SyncConfig) => { + const storedValue = await storage.get(key) + + if (storedValue !== undefined) { + store.set(storedValue) + } store.subscribe(async (value: T) => { await storage.set(key, value) @@ -36,9 +38,10 @@ export interface SyncedConfig { } export const synced = ({key, storage, defaultValue}: SyncedConfig) => { - const store = writable(defaultValue) + const store = writable(defaultValue) as Synced - sync({key, store, storage}) + const syncPromise = sync({key, store, storage}) + store.ready = syncPromise return store }