I'm trying to implement a user registry using auth and firebase database. The idea is that a user log in with his facebook or google account and if he had never entered before, he saves his data and also goes to an instance where he must choose his gender. If it is already registered in the database, it goes directly to the home page. The problem is that when trying to change the status to know if the user was already registered or not, I get the error of this is null
this is the code:
import React, { Component } from 'react';
import firebase from 'firebase';
import {Button, ButtonToolbar} from 'react-bootstrap';
import {facebookProvider, googleProvider} from '../index.js'
import Home from './Home.js'
import Sex from './Sex.js'
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
cont : false,
redirectToSex : false,
redirectToHome : false,
sex : null,
win : 0,
lost : 0
}
this.authWithGoogle = this.authWithGoogle.bind(this);
this.authWithFacebook = this.authWithFacebook.bind(this);
this.addUser = this.addUser.bind(this);
}
addUser() {
const user = firebase.auth().currentUser;
//se inicializa la base de datos
var database = firebase.database();
var ref = database.ref('photos');
//se obtienen los datos de los usuarios ya registrados
ref.on('value', function(data){
//se comparan con el de el usuario actual para saber si ya se registro antes
var users = data.val();
if (users != null){
var key = Object.keys(users);
for (var i=0; i<key.length; i++){
var k = key[i];
if (user.displayName === users[k].username){
this.setState({cont : true});
console.log(this.state.cont);
}
}
}
});
console.log(this.state.cont);
//si no se registro se agregan los datos a la base de datos
if (this.state.cont === false){
var userdata = {
username : user.displayName,
photo : user.photoURL,
sex: null,
win : 0,
lost : 0
}
ref.push(userdata);
this.setState({redirectToSex : true});
}else {
this.setState({redirectToHome : true});
}
}
render() {
if (this.state.redirectToHome === true) {
return(
<Home></Home>
);
}
if (this.state.redirectToSex === true){
return(
<Sex></Sex>
);
}
return(
<div className="loginStyle">
<Button style={{width: "100%"}} bsStyle="primary" onClick={this.authWithFacebook}>Login con facebook</Button>
<hr style={{marginTop:"10px", marginBottom:"10px"}}/>
<Button style={{width: "100%"}} bsStyle="danger" onClick={this.authWithGoogle}>Login con google</Button>
{console.log(this.redirectToHome)}
</div>
);
}
}
(the authWithGoogle and authWithFacebook functions only call the signInWithPopUp function of firebase and if there is no error they call > addUser . Do not add them to avoid unnecessarily lengthening the code)
the error appears after clicking on any of the buttons to login.