Last active
March 6, 2023 17:26
-
-
Save phultquist/e9cb115417398e5cb75e75cfed2b9c4b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This svelte store is a reference to make super quick live and interactive pieces of code. | |
See its announcement at https://www.youtube.com/watch?v=A8jkJTWacow&t=18579s | |
*/ | |
type Options<T> = { | |
validator: (data: T) => void; | |
}; | |
export function live<T>(path: string, initialValue: T, options?: Options<T>) { | |
const store = writable(initialValue, (set) => { | |
let unsubscribe = onDbChange((newData) => { | |
try { | |
options?.validator?.(newData); | |
} catch (e) { | |
console.warn('Data from remote is invalid'); | |
console.error(e); | |
} | |
set(newData); | |
}); | |
return unsubscribe; | |
}); | |
const { subscribe, set } = store; | |
return { | |
set(newData: T) { | |
options?.validator?.(newData); | |
set(newData); | |
}, | |
save() { | |
const data = get(store); | |
updateDb(path, data); | |
}, | |
subscribe | |
}; | |
} |
Totally possible! Could automatically save to the database after debounce. Might be a bit dangerous though. Be careful not to cause extra writes — perhaps deep object comparison could be implemented in the set
method.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What do you think about invoking
updateDb
automatically in the returnedset
function? Probably on a debounce or something similar