Skip to content

Commit

Permalink
reactive localstorage hook
Browse files Browse the repository at this point in the history
  • Loading branch information
kamranasad7 committed Nov 13, 2023
1 parent ee89172 commit 074d62d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/hooks/useLsState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useEffect, useState } from "react";
import SecureLS from "secure-ls";

const useLsState = <T>(key: string, defaultValue?: T): [T, (value: T) => void] => {

const ls = new SecureLS();
const [state, _setState] = useState<T>(ls.get(key) || null);

const setState = (value: T): void => {
ls.set(key, value);
_setState(value);
}

const onStorageChange = (e: StorageEvent) => {
if(e.key == key) { _setState(ls.get(key)); }
}

useEffect(() => {
if(defaultValue && !ls.getAllKeys().includes(key)) { setState(defaultValue); }

window.addEventListener('storage', onStorageChange);
return () => window.removeEventListener('storage', onStorageChange);
}, [])

return [state, setState];
}

export { useLsState };
1 change: 1 addition & 0 deletions lib/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useLsState } from "./hooks/useLsState";

0 comments on commit 074d62d

Please sign in to comment.