diff options
| author | 2024-08-25 04:01:39 +0100 | |
|---|---|---|
| committer | 2024-08-25 04:01:39 +0100 | |
| commit | 12cf4539a6b44989f2132b2fdeccd9c0f0e6028e (patch) | |
| tree | ffc7cff33d58badb3f79b15af9d126b569dc64b3 /thallium-frontend/src | |
| parent | Add redux (diff) | |
Add redux store and authorization slice
Diffstat (limited to 'thallium-frontend/src')
| -rw-r--r-- | thallium-frontend/src/slices/authorization.ts | 25 | ||||
| -rw-r--r-- | thallium-frontend/src/store.ts | 39 | 
2 files changed, 64 insertions, 0 deletions
| diff --git a/thallium-frontend/src/slices/authorization.ts b/thallium-frontend/src/slices/authorization.ts new file mode 100644 index 0000000..6ebc159 --- /dev/null +++ b/thallium-frontend/src/slices/authorization.ts @@ -0,0 +1,25 @@ +import { createSlice } from "@reduxjs/toolkit"; + +const authorizationSlice = createSlice({ +    name: "authorization", +    initialState: { +        voucherToken: null as string | null, +        userToken: null as string | null, +    }, +    reducers: { +        setVoucherToken(state, action: { payload: string }) { +            state.voucherToken = action.payload; +        }, +        setUserToken(state, action: { payload: string }) { +            state.userToken = action.payload; +        }, +        clearToken(state) { +            state.voucherToken = null; +            state.userToken = null; +        } +    }, +}); + +export const { setVoucherToken, setUserToken, clearToken } = authorizationSlice.actions; + +export default authorizationSlice.reducer; diff --git a/thallium-frontend/src/store.ts b/thallium-frontend/src/store.ts new file mode 100644 index 0000000..96c4405 --- /dev/null +++ b/thallium-frontend/src/store.ts @@ -0,0 +1,39 @@ +import { combineReducers, configureStore } from "@reduxjs/toolkit"; + +import authorizationReducer from "./slices/authorization.ts"; + +const rootReducer = combineReducers({ +    authorization: authorizationReducer, +}); + +export const setupStore = (preloadedState?: Partial<RootState>) => { +    return configureStore({ +        reducer: rootReducer, +        preloadedState, +    }); +}; + +const found = localStorage.getItem("authorizationState"); + +let persistedState: RootState["authorization"] = { +    voucherToken: null, +    userToken: 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"); +    localStorage.setItem("authorizationState", JSON.stringify(store.getState().authorization)); +}); | 
