Skip to content

Instantly share code, notes, and snippets.

@belackriv
Last active March 15, 2024 15:29
Show Gist options
  • Save belackriv/2b2c251c3e39d147c086cc1329c366eb to your computer and use it in GitHub Desktop.
Save belackriv/2b2c251c3e39d147c086cc1329c366eb to your computer and use it in GitHub Desktop.
Using Simple Auth State
import { createListenerMiddleware } from "@reduxjs/toolkit";
import { authApi } from './authApi';
import { api } from './baseApi';
import type { RootState } from "../store";
export const authListenerMiddleware = createListenerMiddleware();
authListenerMiddleware.startListening({
matcher: authApi.endpoints.login.matchFulfilled,
effect: (action, listenerApi) => {
localStorage.setItem(
'auth',
JSON.stringify((listenerApi.getState() as RootState).auth)
);
listenerApi.dispatch(api.util.resetApiState());
}
});
authListenerMiddleware.startListening({
matcher: authApi.endpoints.logout.matchFulfilled,
effect: (action, listenerApi) => {
localStorage.removeItem('auth');
listenerApi.dispatch(api.util.resetApiState());
}
});
authListenerMiddleware.startListening({
matcher: authApi.endpoints.userProfile.matchFulfilled,
effect: (action, listenerApi) => {
const token = (listenerApi.getState() as RootState).auth.token;
localStorage.setItem(
'auth',
JSON.stringify({token: token, user: {...action.payload}})
);
}
});
import { createSlice } from '@reduxjs/toolkit';
import { authApi } from '../../services/authApi';
import type { RootState } from '../../store';
import { User } from '../types';
type AccessAndRefreshToken = {
access: string,
refresh: string
}
type AuthState = {
user: User | null
token: AccessAndRefreshToken | null
}
const slice = createSlice({
name: 'auth',
initialState: { user: null, token: null } as AuthState,
reducers: {
tokenReceived: (state, {payload}) => {
state.token = {...state.token, access: payload.access};
},
tokenCleared: (state) => {
state.token = null;
state.user = null;
},
},
extraReducers: (builder) => {
builder.addMatcher(
authApi.endpoints.login.matchFulfilled,
(state, { payload }) => {
state.token = payload.token;
state.user = payload.user;
},
).addMatcher(
authApi.endpoints.logout.matchFulfilled,
(state, { payload }) => {
state.token = null;
state.user = null;
},
).addMatcher(
authApi.endpoints.userProfile.matchFulfilled,
(state, { payload }) => {
state.user = {...payload};
},
)
},
});
export default slice.reducer;
export const { tokenReceived, tokenCleared } = slice.actions;
export const selectCurrentUser = (state: RootState) => state.auth.user;
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import { createReduxHistoryContext } from "redux-first-history";
import { createBrowserHistory } from "history";
import { authListenerMiddleware } from './services/authListenerMiddleware';
import { api } from './services/baseApi';
import authReducer from './account/slices/authSlice';
import uiReducer from './slices/uiSlice';
import usersReducer from './account/slices/usersSlice';
import companiesReducer from './account/slices/companiesSlice';
import businessVerticalsReducer from './account/slices/businessVerticalsSlice';
import companyLocationsReducer from './account/slices/companyLocationsSlice';
import businessUnitVerticalsReducer from './account/slices/businessUnitVerticalsSlice';
import businessUnitsReducer from './account/slices/businessUnitsSlice';
const {
createReduxHistory,
routerMiddleware,
routerReducer
} = createReduxHistoryContext({ history: createBrowserHistory() });
const authState = JSON.parse(localStorage.getItem("auth") || "null");
const entitiesReducer = combineReducers({
users: usersReducer,
companies: companiesReducer,
businessVerticals: businessVerticalsReducer,
companyLocations: companyLocationsReducer,
businessUnits: businessUnitsReducer,
businessUnitVerticals: businessUnitVerticalsReducer,
});
export const store = configureStore({
preloadedState: {
auth: (authState === null)?{ user: null, token: null }:authState
},
reducer: {
router: routerReducer,
[api.reducerPath]: api.reducer,
auth: authReducer,
ui: uiReducer,
entities: entitiesReducer
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(
routerMiddleware,
api.middleware,
authListenerMiddleware.middleware
),
});
export const history = createReduxHistory(store);
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment