working header!
This commit is contained in:
@ -1,42 +1,37 @@
|
||||
import { configureStore, createAction, createReducer } from "@reduxjs/toolkit";
|
||||
import {
|
||||
ReducerType,
|
||||
configureStore,
|
||||
createAction,
|
||||
createReducer,
|
||||
} from "@reduxjs/toolkit";
|
||||
import { setupListeners } from "@reduxjs/toolkit/query";
|
||||
import { AuthApi, User } from "../slice/AuthApi";
|
||||
|
||||
export type authState = {
|
||||
export type AuthDataType = {
|
||||
token: string | null;
|
||||
user: { name: string | null; username: string } | null;
|
||||
};
|
||||
|
||||
const initialAuthState: authState = {
|
||||
const initialAuthDataState: AuthDataType = {
|
||||
token: null,
|
||||
user: null,
|
||||
};
|
||||
|
||||
export type StorePrototype = {
|
||||
AuthApi: ReducerType;
|
||||
auth: AuthDataType;
|
||||
};
|
||||
|
||||
export const updateToken = createAction<string>("auth/updateToken");
|
||||
export const getLocalToken = createAction("auth/getLocalToken");
|
||||
export const updateUser = createAction<User>("auth/updateUser");
|
||||
|
||||
const parseJwt = (token: string): { sub: string; exp: number } => {
|
||||
const base64Url = token.split(".")[1];
|
||||
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const jsonPayload = decodeURIComponent(
|
||||
window
|
||||
.atob(base64)
|
||||
.split("")
|
||||
.map(function (c) {
|
||||
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
|
||||
})
|
||||
.join("")
|
||||
);
|
||||
|
||||
return JSON.parse(jsonPayload);
|
||||
};
|
||||
export const logOut = createAction("auth/logOut");
|
||||
|
||||
export const store = configureStore({
|
||||
reducer: {
|
||||
// Add the generated reducer as a specific top-level slice
|
||||
[AuthApi.reducerPath]: AuthApi.reducer,
|
||||
auth: createReducer(initialAuthState, (builder) => {
|
||||
auth: createReducer(initialAuthDataState, (builder) => {
|
||||
builder.addCase(updateToken, (state, action) => {
|
||||
state.token = action.payload;
|
||||
localStorage.setItem("token", action.payload);
|
||||
@ -50,6 +45,11 @@ export const store = configureStore({
|
||||
builder.addCase(updateUser, (state, action) => {
|
||||
state.user = action.payload;
|
||||
});
|
||||
builder.addCase(logOut, (state) => {
|
||||
localStorage.removeItem("token");
|
||||
state.token = null;
|
||||
state.user = null;
|
||||
});
|
||||
}),
|
||||
},
|
||||
// Adding the api middleware enables caching, invalidation, polling,
|
||||
|
||||
Reference in New Issue
Block a user