Localstorage

This commit is contained in:
Gwilym Inzani 2023-07-05 11:39:14 +01:00 committed by Corwin
parent bf722ecdfa
commit 7decbccbcd
No known key found for this signature in database
2 changed files with 45 additions and 2 deletions

View file

@ -3,6 +3,7 @@ import { Mgba } from "./mgba";
import { BindingsControl, DefaultBindingsSet, Bindings } from "./bindings";
import { styled } from "styled-components";
import { useOnKeyUp } from "./useOnKeyUp.hook";
import { useLocalStorage } from "./useLocalStorage.hook";
const BindingsDialog = styled.dialog`
border-radius: 5px;
@ -21,8 +22,14 @@ const CloseButton = styled.button`
`;
function App() {
const [volume, setVolume] = useState(1.0);
const [bindings, setBindings] = useState(DefaultBindingsSet());
const [volumeState, setVolume] = useState(1.0);
const [bindingsState, setBindings] = useState(DefaultBindingsSet());
const { volume, bindings } = useLocalStorage(
{ volume: volumeState, bindings: bindingsState },
"agbrswebplayer"
);
const [paused, setPaused] = useState(false);
const [showBindings, setShowBindings] = useState(false);

View 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;
}
};