mirror of
https://github.com/italicsjenga/agb.git
synced 2025-01-04 06:01:35 +11:00
Localstorage
This commit is contained in:
parent
bf722ecdfa
commit
7decbccbcd
|
@ -3,6 +3,7 @@ import { Mgba } from "./mgba";
|
||||||
import { BindingsControl, DefaultBindingsSet, Bindings } from "./bindings";
|
import { BindingsControl, DefaultBindingsSet, Bindings } from "./bindings";
|
||||||
import { styled } from "styled-components";
|
import { styled } from "styled-components";
|
||||||
import { useOnKeyUp } from "./useOnKeyUp.hook";
|
import { useOnKeyUp } from "./useOnKeyUp.hook";
|
||||||
|
import { useLocalStorage } from "./useLocalStorage.hook";
|
||||||
|
|
||||||
const BindingsDialog = styled.dialog`
|
const BindingsDialog = styled.dialog`
|
||||||
border-radius: 5px;
|
border-radius: 5px;
|
||||||
|
@ -21,8 +22,14 @@ const CloseButton = styled.button`
|
||||||
`;
|
`;
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const [volume, setVolume] = useState(1.0);
|
const [volumeState, setVolume] = useState(1.0);
|
||||||
const [bindings, setBindings] = useState(DefaultBindingsSet());
|
const [bindingsState, setBindings] = useState(DefaultBindingsSet());
|
||||||
|
|
||||||
|
const { volume, bindings } = useLocalStorage(
|
||||||
|
{ volume: volumeState, bindings: bindingsState },
|
||||||
|
"agbrswebplayer"
|
||||||
|
);
|
||||||
|
|
||||||
const [paused, setPaused] = useState(false);
|
const [paused, setPaused] = useState(false);
|
||||||
|
|
||||||
const [showBindings, setShowBindings] = useState(false);
|
const [showBindings, setShowBindings] = useState(false);
|
||||||
|
|
36
website/src/useLocalStorage.hook.ts
Normal file
36
website/src/useLocalStorage.hook.ts
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
import { useRef, useLayoutEffect, useEffect } from "react";
|
||||||
|
|
||||||
|
export const useLocalStorage = <T>(currentValue: T, appName: string): T => {
|
||||||
|
const initialValue = useRef<T>();
|
||||||
|
|
||||||
|
const isFirstRun = !initialValue.current;
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (!initialValue.current) {
|
||||||
|
try {
|
||||||
|
const storageValue = localStorage.getItem(appName);
|
||||||
|
if (storageValue) {
|
||||||
|
initialValue.current = JSON.parse(storageValue);
|
||||||
|
} else {
|
||||||
|
initialValue.current = currentValue;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
initialValue.current = currentValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
try {
|
||||||
|
if (initialValue.current && currentValue) {
|
||||||
|
localStorage.setItem(appName, JSON.stringify(currentValue));
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}, [currentValue]);
|
||||||
|
|
||||||
|
if (isFirstRun) {
|
||||||
|
return initialValue.current ?? currentValue;
|
||||||
|
} else {
|
||||||
|
return currentValue;
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue