Skip to content

Instantly share code, notes, and snippets.

@ryansolid
Created April 9, 2019 04:13
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ryansolid/c248552369c1ad62b1c61210dfdba014 to your computer and use it in GitHub Desktop.
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