Reputation: 848
I need to organize notification which will tell user, that his session will be end after some minutes. For this after page load I get total session time, and parameter which tells me when I must show notification(for example 1000secs-session time and 60-time which remains till session is end) from api. How I understand I need to organize a timer with setTimeout method. But I can't realize how to organize this mechanism acording to react philosophy. How can it be performed?
Upvotes: 0
Views: 4195
Reputation: 563
In your root component set a timeout and show a notification. I dont know how you get the session time, but lets assume that the session time is just available. Then you can do something like this (using ES6):
const React = require('react');
const PropTypes = require('prop-types');
export class Main extends React.Component
{
constructor(props)
{
super(props);
this.state = {
timerid: -1,
sessionEndsSoon: false,
};
this.getSessionTimeout = this.getSessionTimeout.bind(this);
}
componentDidMount()
{
this.setState({ timerid: this.getSessionTimeout() });
}
componentWillUnmount()
{
clearTimeout(this.state.timerid);
}
getSessionTimeout()
{
if (this.state.timerid)
{
clearTimeout(this.state.timerid);
}
timerid = setTimeout(() =>
{
this.setState({sessionEndsSoon : true});
}, this.props.sessionTimeInMs);
return timerid;
}
render()
{
if(this.state.sessionEndsSoon)
{
return (<p>Session ends soon</p>);
}
return (<p>session active</p>);
}
}
Main.propTypes = {
sessionTimeInMs: PropTypes.number.isRequired,
};
Main.defaultProps =
{
sessionTimeInMs: 1000000,
};
Futhermore you can get the session time from the backend via ajax and update the timeout accordingly.
Upvotes: 1