Skip to content

Commit

Permalink
Add state to local storage
Browse files Browse the repository at this point in the history
  • Loading branch information
kacan98 committed Apr 14, 2024
1 parent fb86604 commit 43322ef
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
11 changes: 8 additions & 3 deletions store/index.ts
Original file line number Diff line number Diff line change
@@ -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<typeof store.getState>;
Expand Down
21 changes: 21 additions & 0 deletions store/localStorage.ts
Original file line number Diff line number Diff line change
@@ -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;
}
}
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 43322ef

Please sign in to comment.