I can't manage to stay logged in | Facebook

Hello everyone. I’m trying to make Facebook Login in my app, the login and the logout is working, but once I login, I cannot manage to keep the user stay logged in. If I refresh the page or close the app and open again, it says I’m not logged in. I can’t find the problem, I will be happy if anyone can explain me what I’m doing wrong.

export class HomePage {
	rootPage: any = HomePage;
	public user:any = null;

	logged ={
		loggedIn: false,
	}

  constructor(public navCtrl: NavController,  private afAuth: AngularFireAuth, private facebook: Facebook, private platform: Platform) {
  	firebase.auth().onAuthStateChanged(function(user) {
	  if (user) {
	    this.logged.loggedIn = true;
        this.user = firebase.auth().currentUser;
	  }
	});
  }

  loginFacebook() {
    if (this.platform.is('cordova')) {
      return this.facebook.login(['email', 'public_profile'])
    .then( response => {
      const facebookCredential = firebase.auth.FacebookAuthProvider
        .credential(response.authResponse.accessToken);

      firebase.auth().signInWithCredential(facebookCredential)
        .then( success => { 
        	this.logged.loggedIn = true;
          	this.user = firebase.auth().currentUser;
        });

    	}).catch((error) => { console.log(error) });
    }
  }

  logout(){
  	this.afAuth.auth.signOut();
  	this.logged.loggedIn = false;
  }
}

Hi @critings, You need to save the facebook API response in app or API side. When user opens app again check if user is logged in or not and on logout clear that data.

You can use window local storage to save data.

1 Like

Hey, I’m half way there. I did it with local storage

.then( success => { 
        	this.logged.loggedIn = true;
          	this.user = firebase.auth().currentUser;
          	window.localStorage.setItem('user', JSON.stringify(this.user));
        });

and then I can access the storage item and it returns me all the user data, but when I try to get the name or the photo is says undefined. this.user.displayName says undefined, but this.user returns me all data. Why is that?

Thanks in advance!

I fixed it, using JSON.parse. Thanks