Skip to content

Instantly share code, notes, and snippets.

@phultquist
Last active March 6, 2023 17:26
Show Gist options
  • Save phultquist/e9cb115417398e5cb75e75cfed2b9c4b to your computer and use it in GitHub Desktop.
Save phultquist/e9cb115417398e5cb75e75cfed2b9c4b to your computer and use it in GitHub Desktop.
/*
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
};
}
@JordanShurmer
Copy link

What do you think about invoking updateDb automatically in the returned set function? Probably on a debounce or something similar

@phultquist
Copy link
Author

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