Skip to content

Instantly share code, notes, and snippets.

@lpshanley
Created June 26, 2020 17:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lpshanley/c987a23c7fe3136d26d42b11b2f68a63 to your computer and use it in GitHub Desktop.
Save lpshanley/c987a23c7fe3136d26d42b11b2f68a63 to your computer and use it in GitHub Desktop.
import { writable } from 'svelte/store'
/**
* Creates a writable store that
* exposes an effect HOC. This
* allows you to debounce a side
* effect.
*
* An example of utility might be
* a typeahead system. Storing form
* data in localStorage or syncing
* a stores state with a database.
*/
export default function storeWithEffect(state, options = {}) {
let { set, update, subscribe } = writable(state)
const config = {
debounce: 400,
effect: null,
...options
}
let side_effect
function effect(state) {
const { effect, debounce } = config
if(typeof effect !== 'function') return state
clearTimeout(side_effect)
side_effect = setTimeout(() => effect(state), debounce)
return state
}
return {
set: state => set(effect(state)),
update: updateFunction => update(state => effect(updateFunction(state))),
subscribe
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment