useLocalStorage for persistant values from Reducer

This commit is contained in:
djmil 2023-11-03 13:32:59 +01:00
parent b237722e82
commit ba7f9ce7d1
3 changed files with 72 additions and 25 deletions

View File

@ -7,12 +7,11 @@ import Leaderboard from "./components/Leaderboard"
import Game from "./components/Game" import Game from "./components/Game"
import About from "./components/About" import About from "./components/About"
import { pollingReducer, pollingDefaults } from './reducer/polling'; import Polling from './reducer/polling';
function App() { function App() {
const [polling, dispatchPolling] = useReducer(pollingReducer, pollingDefaults) const [polling, dispatchPolling] = useReducer(Polling.reducer, Polling.initialState)
console.log('polling', polling)
return <div className="App"> return <div className="App">
<BrowserRouter> <BrowserRouter>
<Header polling={polling} dispatchPolling={dispatchPolling} /> <Header polling={polling} dispatchPolling={dispatchPolling} />

View File

@ -1,32 +1,49 @@
export function pollingReducer(polling, action) { import { useLocalStorage } from './util/PersistentStorage'
const Persistent = (() => {
const [getEnabled, setEnabled] = useLocalStorage('polling.enabled', true);
return {
getEnabled,
setEnabled
}
})(); // <<--- execute
export const pollingGetInitialState = () => {
return {
enabled: Persistent.getEnabled() === 'true',
games: false,
leaderboard: false
}
};
export function pollingReducer(state, action) {
switch (action.type) { switch (action.type) {
case "toggleOnOff": case 'toggleOnOff': return {
return { ...state,
...polling, enabled: Persistent.setEnabled(!state.enabled)
enabled: !polling.enabled
}; };
case "games": case 'games': return {
return { ...state,
...polling,
games: action.value games: action.value
}; };
case "leaderboard": case 'leaderboard': return {
return { ...state,
...polling,
leaderboard: action.value leaderboard: action.value
}; };
default: default:
throw Error("Unknown action: " + action.type); throw Error('Unknown action:' + action.type);
} }
} }
export const pollingDefaults = { const Polling = {
enabled: true, initialState: pollingGetInitialState(), // <<--- execute
reducer: pollingReducer
}
games: false, export default Polling
leaderboard: false,
};

View File

@ -0,0 +1,31 @@
export function useLocalStorage(name, initialValue) {
const get = () => localStorage.getItem(name);
const del = () => localStorage.removeItem(name);
const set = (value) => {
localStorage.setItem(name, value);
return value;
}
if (get() === null) {
set(initialValue);
}
return [get, set, del]
}
export function useSessionStorage(name, initialValue) {
const get = () => sessionStorage.getItem(name);
const del = () => sessionStorage.removeItem(name);
const set = (value) => {
sessionStorage.setItem(name, value);
return value;
}
if (get() === null) {
set(initialValue);
}
return [get, set, del]
}