Update sync implementation to ensure stored value is loaded into svelte
store, before subscription handler is ran
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user