Chan Jing Hong
Chan Jing Hong

Reputation: 2461

React native logout user if they are idle or inactive for a certain period of time

I'm using react-redux and I need to be able to logout the user if they are inactive for 10 minutes (no touches on the screen) or if the app goes into background. How should I do that?

I have tried creating a timer in my root container and updates the reducer that updates every x seconds or so, and used a pan gesture to reset the timer when there are touches. But that didn't work, because everytime the redux state is updated my app will refresh itself.

Anyone have any solutions? I tried looking for an npm package that does something similar but have no luck.

Upvotes: 1

Views: 5895

Answers (3)

pritesh
pritesh

Reputation: 2192

You can use https://facebook.github.io/react-native/docs/appstate to know when the app is in the background or foreground.

So when the App goes background you can dispatch an action setting the current time.

And when the App comes to foreground you check the diff from current time to the dispatched time(when the app went background). You can do whatever you want if the condition matches.

componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
}

componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
}

_handleAppStateChange = (nextAppState) => {
    const { appState } = this.state;
    if (appState.match(/inactive|background/) && nextAppState === 'active') {

        // Compare Current Time with Dispatched Time Here

    } else if (appState.match(/inactive|active/) && nextAppState === 'background') {

        // Dispatch current time here.

    }
    this.setState({appState: nextAppState});
};

Upvotes: 2

Hamza Mazhar
Hamza Mazhar

Reputation: 31

The best way to protect and limited the login time use JWT token to make it secure and time limit of the session you want to close after certain amount of time

Upvotes: -1

kreysix
kreysix

Reputation: 359

You can integrate this npm package react-native-background-timer This can run a block of code (logout function) after the specified interval of time.

Upvotes: 1

Related Questions