Update sync implementation to ensure stored value is loaded into svelte

store, before subscription handler is ran
This commit is contained in:
Matthew Remmel
2025-09-02 10:04:34 -04:00
parent e7a0add8cc
commit 4a4e2e9350
2 changed files with 13 additions and 13 deletions
+5 -5
View File
@@ -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,
+8 -8
View File
@@ -17,12 +17,12 @@ export interface SyncConfig<T> {
storage: StorageProvider
}
export const sync = <T>({key, store, storage}: SyncConfig<T>) => {
storage.get(key).then((value: T | undefined) => {
if (value !== undefined) {
store.set(value)
}
})
export const sync = async <T>({key, store, storage}: SyncConfig<T>) => {
const storedValue = await storage.get(key)
if (storedValue !== undefined) {
store.set(storedValue)
}
store.subscribe(async (value: T) => {
await storage.set(key, value)
@@ -35,10 +35,10 @@ export interface SyncedConfig<T> {
defaultValue: T
}
export const synced = <T>({key, storage, defaultValue}: SyncedConfig<T>) => {
export const synced = async <T>({key, storage, defaultValue}: SyncedConfig<T>) => {
const store = writable<T>(defaultValue)
sync({key, store, storage})
await sync({key, store, storage})
return store
}