Home > Software design >  Way to keep login state using JWT after logged in
Way to keep login state using JWT after logged in

Time:07-29

I'm wondeirng is there a original, and most used way to code "Way to keep logged in state".

Currently, I set log in button to 'MyPage' button after successful logged in.

However, i referesh the web, then this state has gone.

Ah, i'm using React, and using Cookies with Access and Refresh Token, and wondering "Should i use another state to keep logged in information or not."

Before, i used localStorage and set the state manually, such as "isLogin" : "true" state in localStorage.

However, i'm wondering the way to use accessToken which expires automatically in 30 mins. Will there ve a neat way to construct this function?

Thanks !

CodePudding user response:

Do you want to log in again after the relaunch of the browser?

If so, it can be done with Redux store. Here is the link for documentation.

If not, it should be done with session or chrome.storage or something.

CodePudding user response:

You can use redux-persist in your application so that state is maintained even if you are refreshing page after logged in application.

Sample redux store configuration:

import { combineReducers} from 'redux';
import { configureStore } from '@reduxjs/toolkit';
import thunk from 'redux-thunk';
import { persistReducer } from 'redux-persist';
import storage from '@/redux/sync_storage';
import { setupListeners } from '@reduxjs/toolkit/dist/query';
import persistStore from 'redux-persist/lib/persistStore';
import app from '@/redux/slice/appSlice';
const persistConfig = {
  key: 'root',
  storage,
  //blacklist: ['app']
}
const rootReducer = combineReducers({
     app,
    
 
})
const initialState = {}
const persistedReducer = persistReducer(persistConfig, rootReducer)
const store= configureStore({reducer:persistedReducer,initialState,devTools: process.env.NODE_ENV !== 'production',middleware:[thunk]})
setupListeners(store.dispatch);
export const persistor = persistStore(store, {}, () => {
  persistor.persist();
});
export default store;

The below urls will help with the configuration for react application

https://www.npmjs.com/package/@reduxjs/toolkit

https://www.npmjs.com/package/redux-persist

https://kandi.openweaver.com/javascript/rt2zz/redux-persist#Code-Snippets

  • Related