Vue.js with Firebase email must be valid string - firebase

I'm following a tutorial of Vue.js with Firebase.
I'm novice to this and trying to make user account to firebase with Vue.js and I'm getting this error.
Uncaught O {code: "auth/argument-error", message: "createUserWithEmailAndPassword failed: First argument "email" must be a valid string."}
I've already enabled sign-in-method in firebase. Here is my code.
<template>
<div class="signup">
<p>Let's create a new account</p>
<input type="text" v-model="email" placeholder="Email" /><br/>
<input type="password" v-model="password" placeholder="Password" /><br/>
<button v-on:click="signUp">Sign up</button>
<span>or go back to <router-link to="/login">login</router-link>.</span>
</div>
</template>
<script>
import firebase from 'firebase'
export default {
name: 'signup',
data () {
return {
email: '',
password: ''
}
},
methods: {
signUp: () => {
firebase.auth().createUserWithEmailAndPassword(this.email, this.password).then(
(user) => {
alert('Your account has been created!')
},
(err) => {
alert('Opps!' + err.message)
}
);
}
}
}
</script>
When I console.log the email and password in signUp method, I found both the email and password are undefined.

The Problem was arrow functions. Changed ()=> {} to function() {} and now it works. Thanks to #EricGuan's comment.

Related

Unable to add profile info into firebase collection when signing up (vue | firebase)

I'm getting these two errors
TypeError: firebase__WEBPACK_IMPORTED_MODULE_2__.default.firestore(...).collections is not a function
Cannot read property 'user' of undefined
when trying to add user profile data into firebase collections 'profiles' when signing up. Please help.
This is the template section of my 'EditProfile' page.
<template>
<div class="edit-profile">
<section>
<div class="column">
<div class="header" style="font-weight:bold">
Profile Settings
</div>
<div>
<input
type="text"
class="form-control"
placeholder="Full name"
v-model="profile.name"
/>
<input
type="phone"
class="form-control"
placeholder="Phone"
v-model="profile.phone"
/>
<input
type="text"
class="form-control"
placeholder="Billing Address"
v-model="profile.address"
/>
<input
type="text"
class="form-control"
placeholder="Postcode"
v-model="profile.postcode"
/>
<button
#click="updateProfile"
>
Save changes
</button>
</div>
</div>
</section>
</div>
</template>
Here is my script for the above EditProfile page.I haven't really added the code for edit profile bcuz I'm still unaware on how to do that
<script>
import firebase from "firebase";
require("firebase/auth");
export default {
name: "EditProfile",
data() {
return {
profile: {
fullName: null,
phone: null,
address: null,
postcode: null,
},
};
},
methods: {
updateProfile() {},
},
};
</script>
Here is the template for 'RegisterCustomer' page. Here I will be signing up new users.
<template>
<div class="row">
<transition type="text/x-template" id="register-customer">
<div class="modal-mask">
<div class="modal-wrapper">
<div>
<div class="modal-body">
<slot name="body">
<div class="row">
<div class="col-sm-4 off-set">
<form>
<div #click="$emit('close')">
<span class="close">✖</span>
</div>
<h3>Sign up</h3>
<br />
<div class="form-group">
<input
type="text"
class="form-control"
placeholder="fullName"
v-model="fullName"
/>
</div>
<div class="form-group">
<input
type="email"
class="form-control"
placeholder="Email"
v-model="email"
/>
</div>
<div class="form-group">
<input
type="password"
class="form-control"
placeholder="Password"
v-model="password"
#keyup.enter="
onSubmit();
$emit('close');
"
/>
</div>
<div class="modal-footer">
<slot name="footer">
<button
class="btn btn-primary"
type="button"
#click.prevent="onSubmit"
#click="$emit('close')"
>
Sign up
</button>
</slot>
</div>
</form>
</div>
</div>
</slot>
</div>
</div>
</div>
</div></transition
>
</div>
</template>
This is my sign up code in my RegisterCustomer page. I want to add user info into my profiles collection. For now I want to pass the fullName data into my profiles collection.
<script>
import firebase from "firebase";
import "firebase/auth";
export default {
name: "RegisterCustomer",
data: () => ({
fullName: "",
email: "",
password: "",
}),
methods: {
async onSubmit() {
try {
var { user } = await firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.password)
.then(() => {
firebase
.firestore()
.collection("profiles")
.doc(user.uid)
.update({
fullName: this.fullName,
});
console.log("Document successfully written.");
})
.then(() => {
alert("Registration successful.");
console.log(user.uid);
})
.catch((error) => {
console.log(error.message);
});
// this.$router.push("/customer");
} catch (error) {
console.log("error occured", error.message);
alert(error.message);
}
},
},
};
</script>
You need to import the Firebase services you are importing along with the core Firebase App as shown:
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
If you don't import Firestore that way, it'll result in similar issue. Although it was a typo in your case, it's "collection".
The second error Cannot read property 'user' of undefined, is probably because you are trying to get user property from a Promise. Try refactoring your code like this:
async onSubmit() {
try {
const { user } = await firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
await firebase.firestore().collection("profiles")
.doc(user.uid)
.update({
fullName: this.fullName,
});
console.log("Document successfully written.");
alert("Registration successful.");
console.log(user.uid);
} catch (error) {
console.log("error occured", error.message);
alert(error.message);
}
},
I figured out the answer. All I had to do was change .update() to .set() when creating the profiles collection in RegisterCustomer.
Here is the script for RegisterCustomer. Hope someone finds this useful.
<script>
import firebase from "firebase";
import "firebase/auth";
import "firebase/firestore";
export default {
name: "RegisterCustomer",
data: () => ({
fullName: null,
email: null,
password: null,
address: null,
postcode: null,
}),
methods: {
async onSubmit() {
try {
firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.password)
.then((cred) => {
return firebase
.firestore()
.collection("profiles")
.doc(cred.user.uid)
.set({
email: this.email,
fullName: this.fullName,
address: this.address,
postcode: this.postcode,
})
.then(() => {
console.log("Document successfully written.");
});
})
.then(() => {
alert("Registration successful.");
})
.catch((error) => {
console.log(error.message);
});
this.$router.push("/customer");
} catch (error) {
console.log("Error", error.message);
alert(error.message);
}
},
},
};
</script>

Can't update email from Firebase (auth)

I got a Firebase auth you can login and logout.
But I want that the currentUser can change the email.
I have a password reset function that send a email with a link and you can reset your password but It didn't work with the email change.
This is the profile page
Here is the code
<template>
<div class="container">
<div class="card">
<div class="card-header">
<h1>Profile</h1>
</div>
<div v-if="!isHidden" class="alert alert-success" role="alert">
<strong>Email sended</strong>
</div>
<div class="card-body">
<form action="#" #submit.prevent="submit" #click="isHidden = !isHidden">
<div class="form-group row mb-0">
<div class="col-md-7 offset-sm-6 offset-md-7 offset-xl-9">
<input type="submit" class="btn btn-primary" #click="resetPassword" value="Reset your password">
</div>
</div>
</form>
<div class="">
<input type="email" class="form-control" v-model="email">
<input type="submit" class="btn btn-primary" #click="resetEmail" value="Reset your email">
</div>
</div>
</div>
</div>
</template>
<script>
import firebase from "firebase";
/* eslint-disable */
export default {
data() {
return {
email: "",
password: "",
isHidden: true
};
},
methods: {
login(e) {
firebase.auth().signInWithEmailAndPassword(this.email, this.password)
.then(user => {
alert('You are logged in as ' + this.email);
this.$router.push('/index');
location.reload();
},
err => {
alert(err.message);
})
e.preventDefault();
},
resetPassword() {
const auth = firebase.auth();
auth.sendPasswordResetEmail(auth.currentUser.email).then(() => {
console.log('Email send');
// Email sent.
}).catch((error) => {
// An error happened.
console.log(error);
});
},
resetEmail() {
const auth = firebase.auth();
auth.updateEmail(this.email).then(() => {
console.log('Email changed');
// Email sent.
}).catch((error) => {
// An error happened.
console.log(error);
});
}
}
};
</script>
When I run this I get this error:
Uncaught TypeError: auth.updateEmail is not a function
at VueComponent.resetEmail (Profile.vue?5a88:64)
at invoker (vue.runtime.esm.js?2b0e:2023)
at HTMLInputElement.fn._withTask.fn._withTask (vue.runtime.esm.js?2b0e:1822)
What do I do wrong because I read the Firebase doc and checkt on Google but I do something wrong.
The updateEmail() method is not a method of the "root" Firebase Auth service but a method of a User.
So you have to do something along the following lines:
const auth = firebase.auth();
auth.currentUser.updateEmail(this.email).then(() => {...});

Firebase UpdateEmail returning updateEmail failed: First argument "email" must be a valid string

I have a email field in my vue js componont. When the component loads its taking the email value what i have added during the registration time. But when I tried to update my email to a new emai using updateEmail its retruning an error code: "auth/argument-error", message: "updateEmail failed: First argument "email" must be a valid string.".
<template>
<div>
<form #submit.prevent="onUpdateProfile">
<input type="email" v-model="profile.email" placeholder="Enter Your Email..." class="from-input" />
<button type="submit">submit</button>
</form>
</div>
</template>
data() {
return {
profile: {
email: ""
}
};
},
methods:{
onUpdateProfile() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
user.updateEmail({
email: this.profile.email
})
.then(() => {})
.catch(error => {
console.log(error);
});
}
}
},
created() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.profile.email = user.email;
}
}
}
can you try changing this
user.updateEmail({
email: this.profile.email
})
to this?
user.updateEmail(this.profile.email)

How to get the ID of a newly created Firestore document in Vue.js?

Using Vue.js and Firebase I am build the simplest CRUD I can think of.
When I 'create' data from a form I can send it to the database but when I try to update my local array of objects there is no document id, as this is created by firebase when I create a new document. So how can I retrieve the new document id without having to get all the data from the database?
There must be a pattern for this. The only thing I can think of doing is getting 'all' the data from the database again. But is there an easier way?
Is there a way to get the id passed back to the component of a newly created document?
Here is my component with only the necessary bits,
<template lang="html">
<div class="crud">
<h1>I am the crud component</h1>
<div v-for="item in peoples" :key="peoples.id" class="peoples">
<h3>name: {{ item.name}} age: {{ item.age}} id: {{ item.id }} <button #click="deletePeople(item.id)">delete</button> </h3>
</div>
<form #submit.prevent="addPerson()">
<div>
<label for="name">Name:</label>
<input type="text" name="name" v-model="name">
</div>
<div>
<label for="age">Age:</label>
<input type="number" name="age" v-model="age">
</div>
<div>
<button>add person to database</button>
</div>
</form>
</div>
</template>
<script>
import db from '#/firebase/init'
export default {
name: 'Crud',
data(){
return {
msg: 'hello all',
peoples: [],
name: null,
age: null
}
},
methods:{
addPerson(){
console.log('addPerson() method running');
console.log('person: ' + this.name);
db.collection('people').add({
name: this.name,
age: this.age
}).then(() => {
db.collection('people').get().then(snapshot => {
this.peoples = []
snapshot.forEach(doc => {
// console.log(doc.data(), doc.id);
let people = doc.data()
people.id = doc.id
this.peoples.push(people)
})
})
// console.log('push to local data');
// this.peoples.push({ name: this.name, age: this.age})
})
},
Any help would be greatly appreciated,
Thanks
// Add a new document with a generated id.
db.collection("cities").add({
name: "Tokyo",
country: "Japan"
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
https://firebase.google.com/docs/firestore/manage-data/add-data
Here you could simply say this.lastID = docRef.id in the .then() and after that you can simply read out the document with the ID lastID.

The email address is badly formatted firebase vue.js

Getting an error "The email address is badly formatted." when trying to use Vue.js with firebase to create a login page.
Here's my code:
<template>
<div class = "sign-up">
<p> Let's create a new account</p>
<input type="email" v-model="email" placeholder="Email"> <br>
<input type="password" v-model="password" placeholder="Password"> <br>
<button v-on:click="signUp">Sign Up</button>
<br>
</div>
</template>
<script>
import firebase from 'firebase'
export default {
name:'Signup',
data: function() {
return {
email: '',
password: '',
}
},
methods: {
signUp: function() {
firebase.auth().createUserWithEmailAndPassword(this.email, this.password).then(
function (user) {
alert('Your account has been created')
},
function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
}
}
</script>
I did make sure that I have enabled the authentication part at the firebase console .
Don't know why still get this error
Help please
Thank God I solved it.
The problem is solved by adding
firebase.initializeApp(config);
right after
import firebase from 'firebase'
since I have already initialize Firebase in other files
the problem might be caused by javascript loading asynchronously .
This works well. I tired to solve your ones. I have brought official firebase auth sample. Your user was not defined and while importing you must have use {} to prevent .auth() error.
<template>
<div class = "sign-up">
<p> Let's create a new account</p>
<input type="email" v-model="email" placeholder="Email">
<input type="password" v-model="password" placeholder="Password">
<button v-on:click="signUp">Sign Up</button>
</div>
</template>
<script>
import {fb} from '../firebase';
export default {
name:'Signup',
data() {
return {
email: "",
password: "",
}
},
methods: {
signUp: function() {
fb.auth().createUserWithEmailAndPassword(this.email, this.password)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
}
}
</script>

Resources