LocalState Hook
import { createState, createEffect } from 'solid-js'; | |
const LOCAL_STORAGE_KEY = 'todos-solid'; | |
function createLocalState(value) { | |
// load stored todos on init | |
const stored = localStorage.getItem(LOCAL_STORAGE_KEY), | |
[state, setState] = createState( | |
stored ? JSON.parse(stored) : value | |
); | |
// JSON.stringify creates deps on every iterable field | |
createEffect(() => | |
localStorage.setItem( | |
LOCAL_STORAGE_KEY, | |
JSON.stringify(state) | |
)); | |
return [state, setState]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment