Ankush Rishi
Ankush Rishi

Reputation: 3190

React-native: On reload app, user must remain in logged in status

I have a login page, when I click on login button it renders me to a demo page that i created. I am trying to use AsyncStorage so that when i reload the app while i am on the demo page, it should not go back to the login page, it must retain on the demo page itself.

Here is my demo page where i used AsyncStorage:

'use strict';
var React = require('react-native');
var {
    AsyncStorage,
    StyleSheet,
    Text,
    View,
} = React;
var NavigationBar = require('react-native-navbar');
var Demo = React.createClass({

    getData: function()
    {
        AsyncStorage.getItem("isLogin").then((yes)=>{
            this.setState({"isLogin":yes});
        }).done();
    },

    storeData: function(yes)
    {
        AsyncStorage.setItem("isLogin", yes);
        this.setState({"isLogin":yes});
    },

    render: function()
    {
        let context = this;
        var leftButtonConfig = {
          title: 'Logout',
          handler: function onNext() {
            context.props.navigator.pop();
          }
        };

        var titleConfig = {
          title: 'Hello world page!',
        };
        return(
            <View style={{ flex: 1, }}>
      <NavigationBar
        title={titleConfig}
        leftButton={leftButtonConfig}
        style={{borderBottomWidth: 1 / React.PixelRatio.get(), borderBottomColor: 'rgba(0, 0, 0, 0.5)',}} />

            <View style={styles.container}>
        <Text style={styles.header}>
        Hello World
        </Text>
        </View>
        </View>
        );
    }
});
var styles = StyleSheet.create({
    container: {
        flex:1
    },
    header: {
        fontSize: 20,
        fontWeight: 'bold',
        textAlign: 'center'
    }
});

module.exports = Demo;

How can I call this AsyncStorage?

Upvotes: 2

Views: 1031

Answers (1)

Adrian Seungjin Lee
Adrian Seungjin Lee

Reputation: 1666

If you write React component in ES6 style, you can call getData in constructor, which would definitely be called before it first renders its content.

import React, {Component} from 'react';

class Demo extends Component {
    constructor(props) {
        super(props);
        getData();
    }
    getData(){
        AsyncStorage.getItem("isLogin").then((yes)=>{
            this.setState({"isLogin":yes});
        }).done();
    }
    render() {
        return (...);
    }
}

export default Demo; 

This post below describes how to write React classes in ES6 style in detail.

https://toddmotto.com/react-create-class-versus-component/

Upvotes: 2

Related Questions