Created
June 26, 2020 17:29
-
-
Save lpshanley/c987a23c7fe3136d26d42b11b2f68a63 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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