Martin Bucher Martin Bucher - 4 months ago 98
Javascript Question

Firebase Login with React Components

The basic idea is to make a Firebase Login in React.

The components render itself, but they're not working together. The main problem is that the render function doesn't take the «new» states, after the onAuthStateChanged() method is called. What am I doing wrong?

Thank you a lot guys!

var Login = React.createClass ({

getInitialState: function(){
return { loggedIn: 'false' };
},

handleLogIn: function(event){

var email = document.getElementById('email').value;
var password = document.getElementById('password').value;

firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// ERROR HANDLING
var errorCode = error.code;
var errorMessage = error.message;

// [... error handling ...]

});

this.setState({ loggedIn: 'true' });

},

authenticateUser: function(x){

// INITIALIZATION
var config = {
[ ... config stuff ... ]
};
firebase.initializeApp(config);

//CHECKING IF SIGNED IN
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// USER IS SIGNED IN
console.log('authenticateUser(): true');
this.setState({ loggedIn: 'true' });
}
else {
// USER IS SIGNED OUT
console.log('authenticateUser(): false');
this.setState({ loggedIn: 'false' });
}
});
},

whichWindowToShow: function() {
if (this.state.loggedIn === 'unknown'){
return (
<div>
<Loading type='bubbles' color='#e3e3e3' />
</div>
);
}
else if (this.state.loggedIn === 'true'){
return (
<div>
<Backend />
</div>
);
}
else {
return (
<div className="login_wrapper">
<div className="login_box">
<h1>Member Login</h1>
<div className="login_fields">
<input type="text" id="email" name="email" placeholder="mail"/>
<input type="password" id="password" name="password" placeholder="password"/>
<button id="signin" name="signin" onClick={this.handleLogIn}>Login</button>
</div>
</div>
</div>
);
}
},

render: function() {
this.authenticateUser();
return (
<div>
{ this.whichWindowToShow() }
</div>
);
}
}); // END LOGIN

Answer

For all with the same problem/challenge,

THIS is the ULTIMATE FINAL SOLUTION