I have a doubt about how to manage a user's session in React, for example in MVC .NET you only just do this using the Session object (e.g. Session["test"] = "";
), but obviously React can not do this.
I was reading about using the component state, I suppose that sets the state at the principal component and passes this state to other components using props. Also I saw people recommending the use the browser's localStorage
or cookies, but I don't know if this if a good idea or practice.
Is there a better way to manage sessions variables in React than localStorage
or cookies?
Focusing on redux-react-session , the first thing you need to do is add your session reducer. import { combineReducers } from 'redux'; import { sessionReducer } from 'redux-react-session'; const reducers = { // ... your other reducers here ... session: sessionReducer }; const reducer = combineReducers(reducers);
Local state is perhaps the easiest kind of state to manage in React, considering there are so many tools built into the core React library for managing it. useState is the first tool you should reach for to manage state in your components. It can take accept any valid data value, including primitive and object values.
Set a timeout via setTimeout to set the active to false after 13 minutes of inactivity. Everytime the user moves the mouse / touches the screen, reset the timeout. In the main app component, you can do something similar to end a session.
There is a React module called react-client-session
that makes storing client side session data very easy. The git repo is here.
This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).
After installing, just set the desired store type where you mount the root component ...
import { ReactSession } from 'react-client-session';
ReactSession.setStoreType("localStorage");
... and set/get key value pairs from anywhere in your app:
import { ReactSession } from 'react-client-session';
ReactSession.set("username", "Bob");
ReactSession.get("username"); // Returns "Bob"
This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.
jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
res.json({
token
});
user object in here is the user data which you want to keep in the session
localStorage.setItem('session',JSON.stringify(token));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With