aboutsummaryrefslogtreecommitdiffstats
path: root/thallium-frontend/src/store.ts
blob: 30766d0dfcba8be34c26523ca33bda7d13c2a1aa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { combineReducers, configureStore } from "@reduxjs/toolkit";

import authorizationReducer from "./slices/authorization.ts";
import cartReducer from "./slices/cart.ts";

const rootReducer = combineReducers({
    authorization: authorizationReducer,
    cart: cartReducer,
});

export const setupStore = (preloadedState?: Partial<RootState>) => {
    return configureStore({
        reducer: rootReducer,
        preloadedState,
    });
};

const found = localStorage.getItem("authorizationState");

let persistedState: RootState["authorization"] = {
    voucherToken: null,
    userToken: null,
    refreshTask: null,
};

if (found) {
    persistedState = localStorage.getItem("authorizationState") ? (JSON.parse(found) as RootState["authorization"]) : persistedState;
}

const store = setupStore({
    authorization: persistedState,
});

export default store;

export type RootState = ReturnType<typeof rootReducer>;
export type AppStore = ReturnType<typeof setupStore>;

store.subscribe(() => {
    console.log("Serializing state to localStorage");
    const authState = store.getState().authorization;
    localStorage.setItem("authorizationState", JSON.stringify({
        voucherToken: authState.voucherToken,
        userToken: authState.userToken,
    }));
});