How to confirm success of push request in Firebase Web? - javascript

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))

Related

Cannot send data to firebase collection

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" });
}
}

Joi validation react .custom() validation in react

Hello I'm trying to add custom validation to my form using the Joi library.Basically i want to reach to an api and either return error message or not based on the data.
here is my Joi schema
const schema = Joi.object({
email: Joi.string()
.email({ tlds: { allow: false } })
.required(),
firstName: Joi.string().required(),
lastName: Joi.string().required(),
description: Joi.string().min(10).max(250).required().custom(isSad).message({'description.invalid':`the value provided in the description field is sad, please redact it`}),
});
the isSad function passed in the custom() argument
const isSad = (value,helpers) => {
fetch('api url',{
method: "POST",
headers: {
"apikey": "key"
},
body:value
}).then(data => {
return data.json()
}).then(data => {
if(data.Sad > 0.49) {
return helpers.error('description.invalid');
}
}).catch(error => {
console.log('logging the error in catch', error)
})
}
As far as I understand I'm sending 'description.invalid' to the .message() function in the schema where I should use it in the passed object to display a custom message, but for some reason I'm not getting the error message displayed. The field seems to be validated as valid which it shouldn't be in my case if the value received is > 0.49
EDIT: Tried using schema.validateAsync with .external() like so
const isSad = (value,helpers) => {
console.log('logging value',value)
console.log('logging helpers',helpers)
fetch('api',{
method: "POST",
headers: {
"apikey": "apikey"
},
body:value
}).then(data => {
return data.json()
}).then(data => {
if(data.Sad > 0.49) {
throw new Error('Ur description is sad please edit it')
}
}).catch(error => {
console.log('logging the error in catch', error)
})
}
and to the schema i just attach .external(isSad) like so
const schema = Joi.object({
email: Joi.string()
.email({ tlds: { allow: false } })
.required(),
firstName: Joi.string().required(),
lastName: Joi.string().required(),
description: Joi.string().min(10).max(250).required().external(isSad)
});
I also had to convert the code where I use the schema.validateAsync since it now returns data as HTTP response.BUT it still doesn't work I get no response whatsoever from the .external() and the description field is validated ( It's like the .external() is not there at all ).
Found an issue, it says that custom is only for synchronous functions, for async you need to use external.
EDIT1
If I understand it right, and please correct me if not, the problem is that error is not thrown, when it should.
In that case I have done the following. Changed the request and the data.
The console says: logging the error in catch Error: Ur description is sad please edit it. Which looks to me as the expected behavior.
const isSad = (value) => {
console.log("value: ", value);
fetch("https://api.coindesk.com/v1/bpi/currentprice.json", {
method: "GET"
})
.then((data) => data.json())
.then((data) => {
console.log("request data: ", data);
if (value.startsWith(data.chartName)) {
throw new Error("Ur description is sad please edit it");
}
})
.catch((error) => {
console.log("logging the error in catch", error);
});
};
const schema = Joi.object({
email: Joi.string()
.email({ tlds: { allow: false } })
.required(),
firstName: Joi.string().required(),
lastName: Joi.string().required(),
description: Joi.string().min(10).max(250).required().external(isSad)
});
schema.validateAsync({
email: "asf#adf.asdf",
firstName: "adfsdafsdf",
lastName: "asdfasdf",
description: "Bitcoin111"
});
I ended up using .validate() not .validateAsync() and made my own custom function check after Joi has already validated the form.

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})
})

Sequelize. How to use different value of parameters in creation

I'm trying write create user function. I have such code
createUser: function (user) {
return db.User.create({
id: user.id,
username: user.username,
password: sha1(user.password),
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
allow_password: user.allow_password
});
}
but it's correct only when I fill all user's fields. Actually, I strongly need only username and email, but when I put only 2 parameters - I've gotten 500 server error. How I can do other rows implicit?
The answer: you have to convert password before the query
createUser: function (user) {
if(user.password) {
user.password = sha1(user.password);
}
return db.User.create({
id: user.id,
username: user.username,
password: user.password,
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
allow_password: user.allow_password
});
}

beforeCreate function is not executing sequentially

After update my sails (0.10-rc5),
I encountered a problem in beforeCreate function :
beforeCreate : function(values, next){
console.log("Called beforeCreate User ");
console.log(values);
if(!values.password || values.password !== values.confirmation){
return next({
err : ["Password doesn't match password confirmation"]
});
}
bcrypt.genSalt(10, function(err, salt){
console.log("call within bcrypt");
if (err) return next(err);
bcrypt.hash(values.password, salt, function(err, hash){
if(err) return next(err);
values.password = hash;
});
});
Access.findOne()
.where({ level : values.level })
.exec(function(err, level){
console.log("call within findOne");
if(err) return next(err);
values.level = level.id;
});
console.log("after");
console.log(values);
next();
}
However, the output of the above function is as following :
Called beforeCreate User
{ firstName: 'Quad',
lastName: 'Doe',
email: '11#11.com',
password: '123456',
confirmation: '123456',
level: 'admin',
id: '2fa1ba1a-ae1c-4380-9107-3c1f6e8eafb3',
online: false }
after
{ firstName: 'Quad',
lastName: 'Doe',
email: '11#11.com',
password: '123456',
confirmation: '123456',
level: 'admin',
id: '2fa1ba1a-ae1c-4380-9107-3c1f6e8eafb3',
online: false }
call within bcrypt
call within findOne
As you can see, somehow bcrypt.genSalt(.....){} and Access.findOne(...){} were not called prior to after, which is supposed to.
What you are seeing is asynchronous code in action...
Node/Sails does not wait for your callbacks to fire before moving on to the the next task.
You need to "nest" your callbacks so that console.log("AFTER") is called within the last callback.
Take a look at async. It's designed for these types of problems.
Or...
Look into fibers

Categories