Cannot send data to firebase collection - javascript

I'm trying to send data on firebase collection but I can't figure out why it can't be sent. Function called createUserWithEmailAndPassword() works normally. In other functions sending data in firebase collection is working fine when I want to send it, but here it doesn't work for some unknown reason. Is this some bug or what?
My function:
SignUp() {
firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.password);
try {
const unique = this.email;
db.collection("user")
.doc(unique)
.set({
name: this.name,
surname: this.surname,
email: this.email,
birth_date: this.birth_date,
city: this.city,
phone_number: this.phone_number,
});
this.success_register=true;
}
catch(error) {
if ((store.currentUser = null)) this.$router.replace({ name: "signup" });
}
}

Related

Redirecting to home page

I have the next following problem in my vue registration. When I click register it redirects me to the home page. Maybe using some conditions could solve this problem. How can I prevent this from happening? Any ideas?
My Javascript:
register() {
firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.lozinka)
.then(
function() {
console.log('Success');
let id = this.email
db.collection("user")
.doc(id)
.set({
korisnicko_ime: this.korisnicko_ime,
email: this.email,
lokacija: this.lokacija,
ime_objekta: this.ime_objekta,
kontakt: this.kontakt,
})
.then((doc) => {
console.log("Saved", doc)
})
})
.catch(function(error) {
console.error("Error...", error);
if ( store.currentUser=null ) {
this.$router.replace({ name: 'Register'});
}
});
console.log('Continue');
this.$router.replace({ name: 'Home'});
},
I do not know what you are actually trying to achieve but what you are doing is fireing a request, register your callbacks on the request's promise and immediately replace your current route.
register() {
firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.lozinka)
.then(successCallback)
.catch(errorCallback);
this.$router.replace({ name: 'Home'});
}
I guess you probably want to wait for the response of your register request and redirect your user based on whether the promise resolved successfully or with an error?
At first you probably should have a deeper look at
Promises with its async/await syntax
Using const over let/var
async register() {
try {
const registerResponse = await firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.lozinka);
console.log("Success");
const id = this.email;
const collectionResponse = await db
.collection("user")
.doc(id)
.set({
korisnicko_ime: this.korisnicko_ime,
email: this.email,
lokacija: this.lokacija,
ime_objekta: this.ime_objekta,
kontakt: this.kontakt,
});
console.log("Saved", doc);
// After everything was successfull, redirect to home
this.$router.replace({ name: 'Home'});
} catch(error) {
console.error("Error...", error);
if ((store.currentUser = null)) this.$router.replace({ name: "Register" });
}
}

obj.hasOwnProperty is not a function error in a Firebase database query

I am deploying a cloud function in Firebase that acts as a OAuth2 middleware, handling the authorization and getting the token. After getting the access token and user details I want to store the token and user details in the database and also update or create the user. The code is from this example. But I'm always getting the same error message from function logs:
TypeError: obj.hasOwnProperty is not a function
at each (/srv/node_modules/#firebase/database/dist/index.node.cjs.js:553:17)
at validateFirebaseData (/srv/node_modules/#firebase/database/dist/index.node.cjs.js:1511:9)
at /srv/node_modules/#firebase/database/dist/index.node.cjs.js:1528:13
at each (/srv/node_modules/#firebase/database/dist/index.node.cjs.js:554:13)
at validateFirebaseData (/srv/node_modules/#firebase/database/dist/index.node.cjs.js:1511:9)
at /srv/node_modules/#firebase/database/dist/index.node.cjs.js:1528:13
at each (/srv/node_modules/#firebase/database/dist/index.node.cjs.js:554:13)
at validateFirebaseData (/srv/node_modules/#firebase/database/dist/index.node.cjs.js:1511:9)
at /srv/node_modules/#firebase/database/dist/index.node.cjs.js:1528:13
at each (/srv/node_modules/#firebase/database/dist/index.node.cjs.js:554:13)
Below is the function for creating a user
async function createFirebaseAccount(uid, displayName, email, accessToken) {
const databaseTask = admin.database().ref(`/idpAccessToken/${uid}`).set(accessToken);
const userCreationTask = admin.auth().updateUser(uid, {
displayName: displayName,
email: email,
emailVerified: true,
}).catch((error) => {
if (error.code === 'auth/user-not-found') {
return admin.auth().createUser({
uid: uid,
displayName: displayName,
email: email,
emailVerified: true,
});
}
throw error;
});
// execution stops here, when resolving this tasks
await Promise.all([userCreationTask, databaseTask]);
const token = await admin.auth().createCustomToken(uid);
console.log('Created Custom token for UID "', uid, '" Token:', token);
return token;
}
The variables uid, displayName, email and token are a plain text string in all four cases. The token returned from this function is later returned to the calling client using jsonp. I don't understand where this error comes from.

How to confirm success of push request in Firebase Web?

var databaseRef = firebase.database().ref("Test_Applicants/");
databaseRef.push({
firstname: first_name,
middlename: middle_name,
lastname: last_name,
university: university_full_name,
email: email_address,
phone: phone_number,
date: getDate(),
docs: docURL
}, function(error){
//Callback failed
console.error(error);
});
Is this the right approach? How do I receive a variable or an argument from Firebase through a callback or through any other way to confirm that the data was written successfully? I'd like to upload a file if request is successful or return an error message to the user if the write fails.
This should work
var databaseRef = firebase.database().ref("Test_Applicants/");
databaseRef.push({
firstname: first_name,
middlename: middle_name,
lastname: last_name,
university: university_full_name,
email: email_address,
phone: phone_number,
date: getDate(),
docs: docURL
}, function(error){
if (error) {
console.error(error)
return
}
console.log('Push successful')
//add upload function here
});
You can listen child events in this case using following
databaseRef.on('child_added', function(data) {
console.log(data);
});
More info: https://firebase.google.com/docs/database/web/lists-of-data#listen_for_child_events
databaseRef.push().set({name:"john doe",telephone:"25400000000"}).catch((error)=>console.log(error))

Can't call firebase database function inside GoogleSignin signIn function

I'm using react-native-google-signin to achieve google login function. After setting up all the configuration steps, I'm able to get 'user' from GoogleSignin.signIn().then((user) => {...}.
Now I want to check whether this user has already used 'this' google account. Because if yes, I don't need to create the user data in the firebase database. But if not (first time), I need to create the user data inside the Google signin function. Here is my code.
import fire from '../../firebase'
.. ..
GoogleSignin.signIn()
.then((user) => {
console.log('get user'); // I can get user here
// This firebase function can't be called (no reaction)
fire.database().ref('Users').child(user.id).once('value', snapshot => {
console.log('inside function'); // can't log it
if(!snapshot.val()) {
console.log('new'); // can't log it
fire.database().ref('Users').child(user.id).child('User_Data').set({
username: user.name,
email: user.email,
avatar: user.photo
});
}
else {
console.log('old'); // can't log it
fire.database().ref('Users').child(user.id).child('User_Data').update({
username: user.name,
email: user.email,
avatar: user.photo
});
}
});
})
.catch((err) => {
console.log('WRONG SIGNIN', err);
})
.done();
I can only get the 'user' data. No new Google email is created in my Firebase Authentication screen. Also, no new user data is created in my database.
Does anyone have the same issue or the solution? Thanks for any help or idea!
I don't use React so this might not help, but have you tried to re-factor your code to something like this;
function googleSignIn() {
GoogleSignin.signIn()
.then(validateSignIn) // Might need to be `this.validateSignIn`
.catch((err) => {
console.log('WRONG SIGNIN', err);
})
.done();
}
function validateSignIn(user) {
console.log('get user'); // I can get user here
// This firebase function can't be called (no reaction)
fire.database().ref('Users').child(user.id).once('value', snapshot => {
console.log('inside function'); // can't log it
if(!snapshot.val()) {
console.log('new'); // can't log it
fire.database().ref('Users').child(user.id).child('User_Data').set({
username: user.name,
email: user.email,
avatar: user.photo
});
}
else {
console.log('old'); // can't log it
fire.database().ref('Users').child(user.id).child('User_Data').update({
username: user.name,
email: user.email,
avatar: user.photo
});
}
}
This way the validateSignIn function is in it's own function and not encapsulated by your thenable object.

React Native & Firebase : user info not being stored in database

I'm trying to create a new user and store their information in firebase database. I successfully create the user but the user information isn't getting stored in firebase.
The function that is running is handleAuthWithFirebase
The console.log("Storing user") is showing up in the console so I'm not sure why firebase.database().ref().set isn't running.
Here is my code
export function handleAuthWithFirebase (newUser) {
return function (dispatch, getState) {
dispatch(authenticating());
console.log(newUser);
console.log('Signing up user');
var email = newUser.email;
var password = newUser.password;
firebase.auth().createUserWithEmailAndPassword(email, password).catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
}).then(() => {
const user = firebase.auth().currentUser;
// Set user in Firebase
console.log("Storing user")
firebase.database().ref('/users/' + user.uid).set({
name: newUser.displayName,
username: newUser.username,
email: newUser.email
})
}).then(() => {
const user = firebase.auth().currentUser;
dispatch(isAuthed(user.uid))
})
}
}
The problem is that you're missing a child object, so you have to specify it after ref. It would be more helpful if you can post the tree of your database as well, but before try this and figure out yout child.
firebase.database().ref('myRef').child('myChild').set({
name: newUser.displayName,
username: newUser.username,
email: newUser.email
})
Here's what I got working, for those coming across this post.
firebaseApp.auth()
.createUserAndRetrieveDataWithEmailAndPassword(this.state.email, this.state.password)
.then(response => {
firebaseApp.database().ref('users').child(response.user.uid).set({
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
email: this.state.email
});
response.user.sendEmailVerification().then(response => {
AlertIOS.alert('Message', 'Sending email verification to '+this.state.email)
});
this.setState({authenticating: false})
}, error => {
AlertIOS.alert('Error', error.message);
this.setState({authenticating: false})
})

Categories