I am learning React but when I register a user(using createUserWithEmailAndPassword) and try to update the displayName property I get the error as "user1.updateProfile is not a function".
How can I solve this error?
My code:
const register = async (e) => {
if (name.length == 0) {
alert("name cannot be empty");
} else {
const userWithEmailAndPassword = await createUserWithEmailAndPassword(auth, email, password)
.then((auth1) => {
const user1 = auth.currentUser;
user1.updateProfile({
displayName: name
});
})
.catch(error => alert(error.message))
console.log(userWithEmailAndPassword);
}
}
The updateProfile function needs to be imported from Firebase Auth SDK directly when using the Modular SDK as shown below:
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth"
const register = async (e) => {
if (name.length == 0) {
alert("name cannot be empty");
} else {
const { user } = await createUserWithEmailAndPassword(auth, email, password)
console.log(`User ${user.uid} created`)
await updateProfile(user, {
displayName: name
});
console.log("User profile updated")
}
}
Related
I followed this tutorial to setup a firebase auth store in vuex (https://www.youtube.com/watch?v=n9cERWIRgMw&list=PL4cUxeGkcC9jveNu1TI0P62Dn9Me1j9tG&index=10)
However, I'm using Nuxt which causes the last step to break.
My file:
import { auth } from "~/plugins/firebase.js";
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged,
} from "firebase/auth";
export const state = () => ({
user: null,
authIsReady: false,
});
export const mutations = {
setUser(state, payload) {
state.user = payload;
console.log("user state changed:", state.user);
},
setAuthIsReady(state, payload) {
state.authIsReady = payload;
},
};
export const actions = {
async signup(context, { email, password }) {
console.log("signup action");
const res = await createUserWithEmailAndPassword(auth, email, password);
if (res) {
context.commit("setUser", res.user);
} else {
throw new Error("could not complete signup");
}
},
async login(context, { email, password }) {
console.log("login action");
const res = await signInWithEmailAndPassword(auth, email, password);
if (res) {
context.commit("setUser", res.user);
} else {
throw new Error("could not complete login");
}
},
async logout(context) {
console.log("logout action");
await signOut(auth);
context.commit("setUser", null);
},
};
const unsub = onAuthStateChanged(auth, (user) => {
store.commit("setAuthIsReady", true);
store.commit("setUser", user);
unsub();
});
Error:
Uncaught (in promise) ReferenceError: store is not defined
at eval (index.js?9101:56:1)
at eval (index-6de4cbb9.js?3d11:2453:1)
How do I commit a mutation from here? I tried loads of things, like this.$store, $store etc.
I'm trying to implement my signUp screen here is the signup handle that is being called, the signup page calls, and pass in the value to my context page.
const handleSignup = async () => {
setLoading(true)
const user = { fullname, email, password, profilePhoto};
try {
const createdUser = await firebase.createUser(user)
setUser({ ...createdUser, isLoggedIn: true });
} catch (error) {
console.log("Error #signUp: ", error);
} finally {
setLoading(false)
}
};
the firebaseContext page then takes in the value that has been passed in creates the account
const FirebaseContext = createContext();
if(!firebase.apps.length){
firebase.initializeApp(auth);
}
const db = firebase.firestore();
const Firebase = {
getCurrentUser: () => {
return firebase.auth().currentUser
},
createUser: async (user) => {
try{
await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);
const uid = Firebase.getCurrentUser().uid;
let profilePhotoUrl = "default";
await db.collection("users").doc(uid).set({
fullname: user.fullname,
email: user.email,
profilePhotoUrl
})
if(user.profilePhoto){
profilePhotoUrl = await Firebase.uploadProfilePhoto(user.profilePhoto);
}
delete user.password;
return { ...user, profilePhotoUrl, uid};
}catch(error){
console.log("Error #createUser", error.message);
}
},
Exporting the file
import { FirebaseContext, FirebaseProvider, Firebase } from './FirebaseContext';
import { UserContext, UserProvider } from './UserContext';
export { FirebaseContext, Firebase, FirebaseProvider, UserContext, UserProvider };
Importing the file
import { FirebaseContext } from "../context";
I am trying to add custom user claims after user sign up, to define user role, using setCustomUserClaims:
/api/users/addUser.js
export default async (req, res) => {
const { displayName, email, password, role } = req.body;
if (!displayName || !password || !email || !role) {
return res.status(400).send({ message: 'Missing fields' });
}
try {
const { uid } = await admin.auth().createUser({
displayName,
email,
password,
});
await admin.auth().setCustomUserClaims(uid, role);
res.status(201).send(uid);
} catch (error) {
handleError(res, error);
}
};
This code checks for any change in the authentication state and sets user to the currently logged in user:
/utils/use-auth.js
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
setUser(user);
} else {
setUser(false);
// Router.push('/login');
}
});
in my /pages/user/home,jsx:
import { useAuth } from '../../utils/use-auth';
function home() {
const { user } = useAuth();
return (
<div>
<pre>{JSON.stringify(user, null, 4)}</pre>
<AdminLayout componentProps={{ selected: '1' }} Component={HomeContent} />
</div>
);
}
The displayed object doesn't have any custom claims.
when I check the firebase console, I find that the user is actually added.
Try using
admin.auth().setCustomUserClaims(uid, claims).then(() => {
// Do your stuff here
});
And verify the claims like
admin.auth().verifyIdToken(idToken).then((claims) => {
// check claims
if (claims) {
// do your stuff here
}
});
for more info check https://firebase.google.com/docs/auth/admin/custom-claims#node.js
I am unable to save username with AsyncStorage in my app.
I am using Switch component, if the value is true, username is saved and on logout the username should persist.
AsyncStorage returns undefined
// function for user to toggle if username should be saved
toggleRememberMe = value => {
this.setState({ rememberMe: value })
if (value === true) {
//user wants to be remembered.
this.rememberUser();
} else {
this.forgetUser();
}
}
// function to save username
rememberUser = async () => {
try {
await AsyncStorage.setItem('user_userID', this.state.signInEmail);
} catch (error) {
console.log(error)
}
};
// function to get username
getRememberedUser = async () => {
try {
const username = await AsyncStorage.getItem('user_userID');
if (username !== null) {
return username;
}
} catch (error) {
console.log(error)
}
};
// function to forget username or remove
forgetUser = async () => {
try {
await AsyncStorage.removeItem('user_userID');
} catch (error) {
console.log(error)
}
};
// componentDidMount
async componentDidMount() {
const username = await this.getRememberedUser();
console.log(username)
this.setState({
signInEmail: username || "",
rememberMe: username ? true : false });
}
//render
<Switch
trackColor={{true: '#16752A'}}
value={this.state.rememberMe}
onValueChange={(value) => this.toggleRememberMe(value)}
/>
<Text>Remember Me</Text>
How can I resolve this?
I want to create users with the function createUserWithEmailAndPassword and then put the data of that user into my database but it doesn't work.. the user is added to my authentication tab in firebase but not in my database. I also don't get an error.
registerUser.addEventListener('click', function (user) {
event.preventDefault();
closeRegisterForm();
email = registerEmail.value;
password = registerPassword.value;
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function (event) {
var ref = firebase.database().ref("users").child(user.uid).set({
email: user.email,
uid: user.uid
});
})
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
});
});
Hi I was having the exact same problem. But i used a local function to solve it. Something like this:
createNewUser(form) {
//create new user with provided data of the form
this.afAuth.auth.createUserWithEmailAndPassword(form.email, form.password)
.then(function(firebaseUser) {
console.log("User " + firebaseUser.uid + " created successfully!");
updateFirestore(form, firebaseUser.uid);
return firebaseUser;
}).catch(function(error) {
alert(error)
});
function updateFirestore(form, uidNewUser) {
//push data into firestore using the uid provided
let data = {};
data['mail'] = form.email;
data['name'] = form.name;
//se empuja el arreglo data en el documento del usuario
this.afs.collection('users').doc(uidNewUser).set(data);
console.log(data, uidNewUser);
}
}
You refer to user.uid and user.email but never define user. The return type of sign in method createUserWithEmailAndPassword is a user but you define it as event. Also make sure you wait for the db write promise to resolve and catch any errors there as Frank advised.
Working for me:
const val = this.signupForm.value;
this.authService.doRegister(val)
.then(res => {
this.msg = 'You have registered successfully!';
this.msgType = 'success';
this.authService.updateUser(val.name, null)
.then(suc => {
const created = firebase.firestore.FieldValue.serverTimestamp();
const user = {
first_name: val.name,
last_name: '',
email_personal: val.email,
created: created,
updated: created
};
this.userCollection = this.afs.collection<User>('users');
this.userCollection.doc(suc).set(user);
}, err => {
// console.log(err);
});
this.router.navigate(['/']);
}, err => {
this.msg = err.message;
})
const [phone, setPhone] = useState()
const [email, setEmail] = useState()
const [password, setPassword] = useState()
const handleSignUp = async () => {
if (!email == ' ' && !password == ' ') {
try {
const result = await auth().createUserWithEmailAndPassword(email, password)
firestore()
.collection('Users')
.doc(result?.user?.uid)
.set({
email: result?.user?.email,
phoneNumber: phone,
uid: result?.user?.uid,
displayName: result?.user?.email.split('#')[0],
})
.then(() => {
alert('User added!');
});
} catch (error) {
if (error.code === 'auth/email-already-in-use') {
Alert.alert('That email address is already in use!');
}
else if (error.code === 'auth/invalid-email') {
Alert.alert('That email address is invalid!');
}
else {
Alert.alert(error)
}
}
} else {
Alert.alert("Please Enter Your All Field");
}
}