Using:
- Redux Toolkit
- Cookie based login with refresh token
import { useDispatch, useSelector } from "react-redux"; | |
// import { userFetchRefreshedAccessTokenThunk } from redux-thunks-location | |
const App = () => { | |
const dispatch = useDispatch() | |
const { token, tokenExpiresIn, isLoggedIn } = useSelector(reduxAuthUserSlice) | |
// auto refreshing the access token | |
useEffect(() => { | |
if (!isLoggedIn || !tokenExpiresIn) return; | |
if (token === "") return; | |
const expiryTime = tokenExpiresIn - Math.round(Date.now() / 1000); | |
const refreshInterval = setInterval(async () => { | |
// Refresh the access token 60 secs before the access token expires | |
dispatch( userFetchRefreshedAccessTokenThunk() ); | |
}, expiryTime * 1000 - 60); | |
return () => clearInterval(refreshInterval); | |
}, [dispatch, isLoggedIn, tokenExpiresIn, token]); | |
return ( | |
<div> | |
Hello World | |
</div> | |
) | |
} |
import { createSlice, PayloadAction } from "@reduxjs/toolkit"; | |
interface AuthUserSliceState { | |
token: string | null; | |
tokenExpiresIn: number | null; | |
isLoggedIn: boolean; | |
isAuthenticating: boolean; | |
} | |
let initialStateData: AuthUserSliceState; | |
initialStateData = { | |
token: null, | |
tokenExpiresIn: null, | |
isLoggedIn: false, | |
isAuthenticating: false, | |
}; | |
export const authUserSlice = createSlice({ | |
name: "authUser", | |
initialState: initialStateData, | |
reducers: { | |
setUserAccessToken: (state, action: PayloadAction<{ token: string; tokenExpiresIn: number }>) => { | |
state.token = action.payload.token; | |
state.tokenExpiresIn = action.payload.tokenExpiresIn; | |
} | |
setUserToLoggedOut: (state) => { | |
state.token = null; | |
state.isLoggedIn = false; | |
state.isAuthenticating = false; | |
}, | |
} | |
}); | |
export const { setUserAccessToken, setUserToLoggedOut } = authUserSlice.actions; | |
export const authUserReducer = authUserSlice.reducer; |
Sure thing. This was part of a project I discontinued a short while back. This code is an amalgamation of a couple of my repos (nv-v3-redesign being the primary one).
You should be able to view all the React code in the client
folder of the project.
Sure thing. This was part of a project I discontinued a short while back. This code is an amalgamation of a couple of my repos (nv-v3-redesign being the primary one).
You should be able to view all the React code in the
client
folder of the project.
This is no longer valid.
The repository has been renamed and the entire project was rebuilt. With it the server folder was scrapped leaving only the client application, moving it into the root directory.
i want all code if you can share it