From 43322efe3b4552dbe63d98c4da666dd3bc3eabc5 Mon Sep 17 00:00:00 2001 From: kacan98 Date: Sun, 14 Apr 2024 14:04:16 +0200 Subject: [PATCH] Add state to local storage --- store/index.ts | 11 ++++++++--- store/localStorage.ts | 21 +++++++++++++++++++++ tsconfig.json | 2 +- 3 files changed, 30 insertions(+), 4 deletions(-) create mode 100644 store/localStorage.ts diff --git a/store/index.ts b/store/index.ts index bd6050a..0bad690 100644 --- a/store/index.ts +++ b/store/index.ts @@ -1,18 +1,23 @@ -import { configureStore } from "@reduxjs/toolkit"; +import { combineReducers, configureStore } from "@reduxjs/toolkit"; import { buyingSlice } from "./calculatorSlices/buying.ts"; import { futurePredictionsSlice } from "./calculatorSlices/futurePreditions.ts"; import { rentingSlice } from "./calculatorSlices/renting.ts"; +import { loadFromLocalStorage, saveToLocalStorage } from "./localStorage.ts"; -const reducer = { +const reducer = combineReducers({ buying: buyingSlice.reducer, renting: rentingSlice.reducer, futurePredictions: futurePredictionsSlice.reducer, -}; +}); + +const persistedState = loadFromLocalStorage(); export const store = configureStore({ reducer, + preloadedState: persistedState, }); +store.subscribe(() => saveToLocalStorage(store.getState())); // Infer the `RootState` and `AppDispatch` types from the store itself export type RootState = ReturnType; diff --git a/store/localStorage.ts b/store/localStorage.ts new file mode 100644 index 0000000..04f82bb --- /dev/null +++ b/store/localStorage.ts @@ -0,0 +1,21 @@ +import { RootState } from "./index"; + +export function saveToLocalStorage(state: RootState) { + try { + const serializedState = JSON.stringify(state); + localStorage.setItem("state", serializedState); + } catch (e) { + console.warn(e); + } +} + +export function loadFromLocalStorage() { + try { + const serializedState = localStorage.getItem("state"); + if (serializedState === null) return undefined; + return JSON.parse(serializedState); + } catch (e) { + console.warn(e); + return undefined; + } +} diff --git a/tsconfig.json b/tsconfig.json index 9d17839..2b7d68e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -21,7 +21,7 @@ "noFallthroughCasesInSwitch": true }, - "include": ["src", "vite.config.ts"], + "include": ["src", "vite.config.ts", "store"], "references": [{ "path": "./tsconfig.node.json" }], "parserOptions": { "ecmaVersion": "latest",