Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native and parse, currentuser is null after login and cmd+R

I'm having a problem with React Native and Parse JS SDK.
And I'm using ParseReact

I have built a login, sign up and a main view, Sign up and log in works well but after i logged in -> directed to main view and when I refresh the app (CMD+R) in my simulator, it brings me back to the login view again, i should be brought to Main view.

As you can see I have set a state for initialComponent:

this.state = {        
      InitialComponent : ((!currentUser) ? LoginView : MainView)
};

This allows my navigator to check for currentUser is null then load LoginView as initial component, else set Main View(user logged in)

'use strict';
var React = require('react-native');
var MainView = require('./MainView');
var LoginView = require('./LoginView');


var Parse = require('parse').Parse;
var ParseReact = require('parse-react');
Parse.initialize("mykey", "mykey");


var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableHighlight,
  Navigator,
  Component
} = React;


class MyApp extends Component {
    constructor(props) {
      super(props);

      var currentUser = Parse.User.current();
      console.log('Current User:' + currentUser);

      this.state = {        
        InitialComponent : ((!currentUser) ? LoginView : MainView)
      };
    }

   render() {
        return (
            <Navigator
              initialRoute={{
                 name : 'StatusList',
                 component: this.state.InitialComponent
              }}
              configureScene = {() =>{
                return Navigator.SceneConfigs.FloatFromRight;
              }}
              renderScene={(route, navigator) =>{
                if(route.component) {
                  return React.createElement(route.component, {navigator});
                }
              }}/>

        );
    }
}

AppRegistry.registerComponent('MyApp', function() { return MyApp });

In my Xcode console, i kept getting current user is null after each refresh even though i have previously logged in. On my parse app, I can see new session has been created.

In my LoginView.

'use strict';

var React = require('react-native');
var SignUp = require('./SignUp');
var MainView = require('./MainView');

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableHighlight,
  Navigator,
  AlertIOS,
  Component
} = React;

var styles = StyleSheet.create({
  container : {
      flex: 1,
      padding: 15,
      marginTop: 30,
      backgroundColor: '#0179D5',
   },
  text: {
    color: '#000000',
    fontSize: 30,
    margin: 100
  },

  headingText: {
    color: '#fff',
    fontSize: 40,
    fontWeight: '100',
    alignSelf: 'center',
    marginBottom: 20,
    letterSpacing: 3
  },

  textBox: {
    color: 'white',
    backgroundColor: '#4BB0FC',
    borderRadius: 5,
    borderColor: 'transparent',
    padding:10,
    height:40,
    borderWidth: 1,
    marginBottom: 15,
  },

  greenBtn: {
    height: 36,
    padding: 10,
    borderRadius: 5,
    backgroundColor: '#2EA927',
    justifyContent: 'center'
  },

  signUpButton: {
    marginTop: 10,
    height: 36,
    padding: 10,
    borderRadius: 5,
    backgroundColor: '#FF5500',
    justifyContent: 'center'

  },

  btnText: {
    color : '#fff',
    fontSize: 15,
    alignSelf: 'center'
  },

  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },

   loginForm : {
      flex:1,
      marginTop:100
   }
});

class LoginView extends Component {

    constructor(props) {
      super(props);
      this.state = {
        username: '',
        password: ''
      };

    }

    checkLogin() {
        var success = true;
        var state = this.state;
        for(var key in state){
          if(state[key].length <= 0){
            success = false;
          }
        }

        if(success) {
          this._doLogin();
        } else {
          //show alert
          AlertIOS.alert('Error','Please complete all fields',
            [{text: 'Okay', onPress: () => console.log('')}]
          );
        }
    }

    goMainView() {
      this.props.navigator.push({
        title: "Home",
        component: MainView
      });
    }

    goSignUp() {
      this.props.navigator.push({
        title: "Sign Up",
        component: SignUp
      });
    }

    _doLogin() {
      var parent = this;
      Parse.User.logIn(this.state.username, this.state.password, {
        success: function(user) {
            parent.goMainView();
        },
        error: function(user, error) {
          AlertIOS.alert('Login Error', error.message,
            [{text: 'Okay', onPress: () => console.log('')}]
          );
        }
      });
    }

    onUsernameChanged(event) {
      this.setState({ username : event.nativeEvent.text });
    }

    onPasswordChanged(event) {
      this.setState({ password : event.nativeEvent.text });
    }

    render() {
       return(
          <View style={styles.container}>
            <View style={styles.loginForm}>
                <Text style={styles.headingText}>
                  MyStatus
                </Text>

               <TextInput style={styles.textBox}
                placeholder='Username'
                onChange={this.onUsernameChanged.bind(this)}
                placeholderTextColor='#fff'
                autoCorrect={false}
               >
               </TextInput>

               <TextInput style={styles.textBox}
                placeholder='Password'
                onChange={this.onPasswordChanged.bind(this)}
                placeholderTextColor='#fff'
                password={true}
               >
               </TextInput>

               <TouchableHighlight style={styles.greenBtn}
                  underlayColor='#33B02C'
                  onPress={this.checkLogin.bind(this)}>
                    <Text style={styles.btnText}>Login</Text>

                </TouchableHighlight>


                <TouchableHighlight style={styles.signUpButton}
                  underlayColor='#D54700'
                  onPress={this.goSignUp.bind(this)}>
                    <Text style={styles.btnText}>Sign Up</Text>

                </TouchableHighlight>
            </View>

          </View>
        );
    }
}

module.exports = LoginView;

Am I doing it the wrong way? Kindly advice. Or is it something wrong with parse localstorage/session?

like image 434
ElsT Avatar asked May 28 '15 05:05

ElsT


2 Answers

Because React Native only provides asynchronous storage, we're forced to make Parse.User.current() an asynchronous call that returns a Promise. Since you're already using Parse+React, it's really easy to handle this. Your component that changes based upon whether the user is logged in or not (MyApp) should subscribe to ParseReact.currentUser. This stays synchronized with the current user, and allows your component to automatically update the moment the user logs in or out. For a demo of this, look at the AnyBudget demo in the GitHub repo:

like image 120
Andrew I Avatar answered Nov 13 '22 01:11

Andrew I


In react-native...

import Parse from 'parse/react-native';

Parse.User.currentAsync()
.then((currentUser)=>{
    if (currentUser) {
        Alert.alert('', JSON.stringify(currentUser))
    }
});
like image 36
Andre Almeida Avatar answered Nov 13 '22 03:11

Andre Almeida