Skip to content

Commit ce16c9c

Browse files
committed
store settings in localStorage
1 parent 9de41a3 commit ce16c9c

1 file changed

Lines changed: 28 additions & 5 deletions

File tree

src/stores/SettingsStore.ts

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ import Store from '@/stores/Store'
22
import { Action } from '@/stores/Dispatcher'
33
import { SetCustomModelEnabled, UpdateSettings } from '@/actions/Actions'
44

5+
const STORAGE_KEY = 'settings'
6+
57
export interface Settings {
68
showDistanceInMiles: boolean
7-
drawAreasEnabled: boolean
9+
drawAreasEnabled: boolean // temporary, not persisted to localStorage
810
gpxExportRte: boolean
911
gpxExportWpt: boolean
1012
gpxExportTrk: boolean
@@ -18,24 +20,45 @@ export const defaultSettings: Settings = {
1820
gpxExportTrk: true,
1921
}
2022

23+
function loadSettings(): Settings {
24+
try {
25+
const stored = localStorage.getItem(STORAGE_KEY)
26+
if (stored) return { ...defaultSettings, ...JSON.parse(stored) }
27+
} catch {
28+
// localStorage unavailable
29+
}
30+
return defaultSettings
31+
}
32+
33+
function saveSettings(settings: Settings): void {
34+
try {
35+
const { drawAreasEnabled, ...persistent } = settings
36+
localStorage.setItem(STORAGE_KEY, JSON.stringify(persistent))
37+
} catch {
38+
// localStorage unavailable
39+
}
40+
}
41+
2142
export default class SettingsStore extends Store<Settings> {
2243
constructor() {
23-
super(defaultSettings)
44+
super(loadSettings())
2445
}
2546

2647
reduce(state: Settings, action: Action): Settings {
48+
let newState = state
2749
if (action instanceof SetCustomModelEnabled) {
2850
if (!action.enabled && state.drawAreasEnabled)
29-
return {
51+
newState = {
3052
...state,
3153
drawAreasEnabled: false,
3254
}
3355
} else if (action instanceof UpdateSettings) {
34-
return {
56+
newState = {
3557
...state,
3658
...action.updatedSettings,
3759
}
3860
}
39-
return state
61+
if (newState !== state) saveSettings(newState)
62+
return newState
4063
}
4164
}

0 commit comments

Comments
 (0)