Created
April 9, 2019 04:13
-
-
Save ryansolid/c248552369c1ad62b1c61210dfdba014 to your computer and use it in GitHub Desktop.
LocalState Hook
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 { 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