Skip to content

Commit

Permalink
Merge pull request #30 from VitorLuizC/master
Browse files Browse the repository at this point in the history
Watch changes on storage and change state (closes #27)
  • Loading branch information
dance2die authored Nov 24, 2019
2 parents eec2a7b + 177005e commit c43a571
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,38 @@
import { Dispatch, useState } from 'react';
import { Dispatch, useCallback, useEffect, useState } from 'react';

export default function useLocalStorage(
key: string,
initialValue: string = ''
): [string, Dispatch<string>] {
const [value, setValue] = useState(
() => localStorage.getItem(key) || initialValue
() => window.localStorage.getItem(key) || initialValue
);

const setItem = (newValue: string) => {
setValue(newValue);
window.localStorage.setItem(key, newValue);
};

useEffect(() => {
const newValue = window.localStorage.getItem(key);
if (value !== newValue) {
setValue(newValue || initialValue);
}
});

const handleStorage = useCallback(
(event: StorageEvent) => {
if (event.key === key && event.newValue !== value) {
setValue(event.newValue || initialValue);
}
},
[value]
);

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

return [value, setItem];
}

0 comments on commit c43a571

Please sign in to comment.