Javascript and Firebase 3 - Create a user with email and password

I am trying to create a registration system with jquery and firebase, and the problem I am having problems with does not know what 'call to firebase' returns. Let me show you in my code:

HTML (simplified by removing irrelevant code):

<div id="registerForm">
    <input type="text" id="userEmail" placeholder="Email"> 
    <input type="password" id="userPass" placeholder="Password"> 
    <button type="button" id="register">Register</button> 
</div>

JQuery (again, only showing code related to Firebase and registration):

<script src=" /* Jquery url */ "></script>
<script src=" /* Firebase url */ "></script>
<script>

    // Initialize Firebase
    var config = {
        apiKey: "*my api key*",
        authDomain: "*myProject*.firebaseapp.com",
        databaseURL: "https://*myProject*.firebaseio.com",
        storageBucket: "*myProject*.appspot.com",
    };
    firebase.initializeApp(config);
</script>
<script>
    $('#register').click(function() {

        var email = $('#userEmail');    
        var pass = $('#userPass');      

        if(email.val() && pass.val()){
            // this is where I stop knowing how all this firebase stuff works


            firebase.auth().createUserWithEmailAndPassword(email.val(), pass.val()).catch(function(error) {
                var errorCode = error.code;
                var errorMessage = error.message;
                console.log(errorCode + ' - ' + errorMessage);
            });

            // This is where it doesn't wanna work. Please check the first paragraph below 
            // for the explanation of how it doesn't work.
            console.log('this message shouldn\'t show if there wasn\'t an error.'); //This fires before firebase.auth()... for some reason
            if(error) {
                console.log('there was an error');
            } else {
                console.log('everything went fine');
            }                 
        } else {
            console.log('fill in both fields');
        }  
    });
</script>

if-else, , firebase.auth. , , , dDdails dddails .., , , , firebase.auth. , , , firebase, - if (firebase.auth.success( - )) {} else {}.

, , , firebase, , . , , / firebase , , , firebase.

, /, , SO, .

, !

+4
1

createUserWithEmailAndPassword - assync, .then() .catch(), - . , - , firebase if(error).

, :

if(email.val() && pass.val()){

    firebase.auth().createUserWithEmailAndPassword(email.val(), pass.val()).then(function(user){
        console.log('everything went fine');
        console.log('user object:' + user);
        //you can save the user data here.
    }).catch(function(error) {
        console.log('there was an error');
        var errorCode = error.code;
        var errorMessage = error.message;
        console.log(errorCode + ' - ' + errorMessage);
    });

} else {
    console.log('fill in both fields');
}  
+8

Source: https://habr.com/ru/post/1648930/


All Articles