wms-bc-react-session
v10.5.35
Published
Create and mantain a sessions in react, compatible with React Router
Downloads
65
Readme
Create and maintain persisten login sessions on the browser (even if the website is refreshed). Checkout the live demo.
Note: Extremely easy integration with React Router.
Installation
$ npm i --save bc-react-session
Usage
- Open a session by doing
Session.login();
:
import {Session} from 'bc-react-session';
Session.start({
payload: {
// (optional) any info you want to save on the persisten session
},
expiration: 86400000; // (optional) defaults to 1 day
});
- Close the session by doing
Session.destroy();
:
import {Session} from 'bc-react-session';
Session.destroy();
- Retrieve the session and payload from anywhere
import {Session} from 'bc-react-session';
const session = Session.get();
const { payload } = Session.get();
console.log(session.isValid); // will be true if is not expired or innactive
console.log(payload); // anything you have set on the session payload is stored here
That is it!!
Some other functionalities:
- Listen to session changes
// listen to session changes
const unsubscribe = Session.onChange((session) => {
console.log(session);
if(session.expired) console.log('The session has expired')
if(session.autenticated) console.log('No one has logged in')
});
//unsubscribe to session changes if needed
unsubscribe();
- Wait for session expiration callback
// you need to enforce before calling the login method.
Session.onExpiration((session) => session.destroy()); //you can destroy the session if it expires
- Change reset the session payload whenever you want
import {Session} from 'bc-react-session';
// pass a new username that will override previous one (if any)
Session.setPayload({
username: 'alesanchezr'
});
- Check session expiration
const session = Session.get();
console.log(session.expired); // boolean
- Make a Private Route using react router
The library brings a component called <PrivateRoute />
to make your routes private without any extra code.
import {PrivateRoute} from 'bc-react-session';
<BrowserRouter>
<div>
<PrivateRoute exact path='/profile' component={PrivateLayout} />
</div>
</BrowserRouter>