Stian Fredrik Aune
1 year ago
3 changed files with 48 additions and 1 deletions
-
31webui-react/src/hooks/storage.ts
-
14webui-react/src/pages/IndexPage.tsx
-
4webui-react/src/pages/PlayPage.tsx
@ -0,0 +1,31 @@ |
|||||
|
import {Dispatch, SetStateAction, useEffect, useState} from "react"; |
||||
|
|
||||
|
function loadData<T>(key: string, defValue: T): T { |
||||
|
const newData = window.localStorage.getItem(`ykonsole2.${key}`); |
||||
|
if (newData === null) { |
||||
|
return defValue; |
||||
|
} |
||||
|
|
||||
|
return JSON.parse(newData) as T; |
||||
|
} |
||||
|
|
||||
|
export default function useLocalStorage<T>(key: string, defValue: T): [T, Dispatch<SetStateAction<T>>] { |
||||
|
const [data, setData] = useState(() => loadData(key, defValue)); |
||||
|
|
||||
|
useEffect(() => { |
||||
|
window.localStorage.setItem(`ykonsole2.${key}`, JSON.stringify(data)); |
||||
|
}, [key, data]); |
||||
|
|
||||
|
useEffect(() => { |
||||
|
const callback = () => { |
||||
|
setData(loadData(key, defValue)); |
||||
|
}; |
||||
|
|
||||
|
window.addEventListener("storage", callback); |
||||
|
return () => { |
||||
|
window.removeEventListener("storage", callback); |
||||
|
}; |
||||
|
}, [key, defValue]); |
||||
|
|
||||
|
return [data, setData]; |
||||
|
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue