I have done the firebase auth and to save the same data in the firebase database. As shown in the image below, I want the same id which is created while login to get display on the database. I should get the same id if the login is successful.
constructor(props) {
super(props);
this.state = { email: '', password: '', error:
'',user:'',confirmpassword:'' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
static navigationOptions = {
title: 'Login',
};
state = { loggedIn: null };
handleChange(e) {
this.setState({
email: e.nativeEvent.text,
password: e.nativeEvent.textpassword,
user: e.nativeEvent.textuser,
confirmpassword: e.nativeEvent.textconfirmpassword,
});
}
handleSubmit(email,password,user) {
db.ref('sevenup-a1db1/').push({
email:this.state.email,
password:this.state.password,
user:''
}).then((data)=>{
console.log('data ' , data)
Alert.alert(
'Item saved successfully'
);
}).catch((error)=>{
console.log('error ' , error)
})
this.setState({ email, password,user });
}
The above code is for saving the data in the firebase database.
componentDidMount() {
let config = {
apiKey: "AIzaSyDPVoCjlIlLj1xrgros7hPjF8kkqsD4bSM",
authDomain: "sevenup-a1db1.firebaseapp.com",
databaseURL: "https://sevenup-a1db1.firebaseio.com",
projectId:"sevenup-a1db1",
storageBucket: "sevenup-a1db1.appspot.com",
messagingSenderId: "144328588028",
appId: "1:144328588028:web:2e5addaf8b3e83ad"
};
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({ loggedIn: true })
} else {
this.setState({ loggedIn: false })
}
})
}
onButtonPress() {
this.setState({ error: '', loading: true })
const { email, password } = this.state;
firebase.auth().signInWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch((error) => {
let errorCode = error.code
let errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
this.onLoginFailure.bind(this)('Weak password!')
} else {
this.onLoginFailure.bind(this)(errorMessage)
}
});
});
}
The above code is for saving the data in firebase auth
I want that after successful login data should be saved in the database successfully. The same id should be displayed in the firebase database which is displayed in firebase auth.
Related
What im doing wrong here and why im getting this error, retrieving extra info that i saved with createUserWithEmailAndPassword
SignUP form details
const {email, password } = this.state;
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((data) => {
const { user } = data;
if(user){
firebase.database().ref('Users/Trainers/' + user.uid).set({
email: this.state.email,
firstName: this.state.firstName,
lastName: this.state.lastName,
role: this.state.role,
datecreated: Date.now()
});
this.props.history.push('/trainerSignin');
}
}).catch((error) => {
this.setState({ error: error });
});```
Profile Page Details
firebase.auth().onAuthStateChanged(user => {
if(user){
const db = firebase.database().ref('Users/Trainers/' + user.uid).once('value', snap => {
console.log(user.email);
console.log(user.firstName);
})
}
})
Here is my DB
I have been stuck forever to create many to many relation between user and project. Many people told that array is better than map but I don't really know how to start. So which is better for this one ? I can't submit into projNo's child and can't select the project from the collection "project". The drop-down shows the projNo from "project" collection but I can't change it to a new value.
import React, { Component } from 'react';
import fire from '../config/Fire';
import { Link } from 'react-router-dom';
import Navigation from '../components/Navigation';
class EditUser extends Component {
constructor(props) {
super(props);
this.unsubscribe = null;
this.state = {
key: '',
authority: '',
name: '',
email: '',
password: '',
projNo: {projNo1: '', projNo2: '', projNo3: ''},
project: []
};
}
onCollectionUpdate = (querySnapshot) => {
const project = [];
querySnapshot.forEach((doc) => {
const { projNo } = doc.data();
project.push({
key: doc.id,
doc, // DocumentSnapshot
projNo
});
});
this.setState({
project
});
}
componentDidMount() {
const ref = fire.firestore().collection('user').doc(this.props.match.params.id);
ref.get().then((doc) => {
if (doc.exists) {
const user = doc.data();
this.setState({
key: doc.id,
authority: user.authority,
name: user.name,
email: user.email,
password: user.password,
projNo: user.projNo
});
} else {
console.log("No such document!");
}
});
this.unsubscribe = fire.firestore().collection('project').onSnapshot(this.onCollectionUpdate);
}
onChange = (e) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState({user:state});
}
onSubmit = (e) => {
e.preventDefault();
const { authority, name, email, password, projNo, projNo1, projNo2, projNo3 } = this.state;
const updateRef = fire.firestore().collection('user').doc(this.state.key);
updateRef.set({
authority,
name,
email,
password,
projNo,
projNo1,
projNo2,
projNo3
}).then((docRef) => {
this.setState({
key: '',
authority: '',
name: '',
email: '',
password: '',
projNo: { projNo1: '', projNo2: '', projNo3: '' }
});
this.props.history.push("/show/"+this.props.match.params.id)
})
.catch((error) => {
console.error("Error adding document: ", error);
});
}
render() {
return (
<div>
...
</div>
);
}
}
export default EditUser;
Image for the database
If you just want to show that a user is connected to a set of projects then I would switch to an array.
To add and remove projects from an array in firestore you can refer to the firebase docs here: https://firebase.google.com/docs/firestore/manage-data/add-data?authuser=0#update_elements_in_an_array
So when you create the user just switch to settings an array, like so:
updateRef.set({
authority,
name,
email,
password,
projNo: [projNo1,projNo2,projNo3]
})
In the future, if you want to atomically add or remove projects from the projNo array, this can be achieved like so:
// Add
updateRef.update({
projNo: firebase.firestore.FieldValue.arrayUnion("projNo16")
});
// Remove
updateRef.update({
projNo: firebase.firestore.FieldValue.arrayRemove("projNo1")
});
Remember, you will need to import firebase into the file where you are calling the above otherwise you can't use FieldValue methods.
I'm running this code in my react app:
componentDidMount() {
modelInstance.addObserver(this);
modelInstance.getSignInStatus().then((user)=>{
this.setState({
userName: user !== false ? user.displayName : "Sign in",
logged_in: user !== false ? true : false
});
});
}
And here is modelInstance.getSignInStatus():
this.getSignInStatus = function () {
return new Promise((resolve, reject)=>{
firebase.auth().onAuthStateChanged(function(user){
if (user){
resolve(user);
}
else {
resolve(false);
}
});
});
}
What happens is that this.state.userName is set to null, meaning that user.displayName is null. Why is this?
state = {
username: "",
email: "",
passwordOne: "",
passwordTwo: "",
error: null
};
onSubmit = event => {
const {username, email, passwordOne} = this.state;
const {history} = this.props;
auth
.createUserWithEmailAndPassword(email, password);
.then(authUser => {
db.doCreateUser(authUser.uid, username, email).then(() => {
//you should clear your state fields here, for username / email etc
console.log(authUser);
//redirect user
history.push(routes.HOME);
});
})
.catch(error => {
this.setState({error});
});
event.preventDefault();
};
const auth = firebase.auth();
const db = firebase.database();
in order to acess doCreateUser
const doCreateUser = (id, username, email) =>
db.ref(`users/${id}`).set({
uid:id,
username,
email,
});
I would use setState for checking the auth status like so:
firebase.auth().onAuthStateChanged(function(user){
if (user){
this.setState({user});
}
}
Then you want the state of the displayName of the current user
componentDidMount() {
modelInstance.addObserver(this);
modelInstance.getSignInStatus().then((user)=>{
this.setState({
userName: this.state.user ? this.state.user.displayName : "Sign in",
logged_in: this.state.user ? true : false
});
});
}
Obviously there has to be a name in the displayName property, If not you would have to update it. Let me know how this turns out.
I build some authentication app including input username, password on firebase. But nothing happen after i press on Log in button on my application. It only shows "Authentication Failed".
class LoginForm extends Component {
state = {
email: '',password: '',error: '',loading: false
};
onButtonPress() {
const { email, password } = this.state;
this.setState({ error: '', loading: true });
firebase.auth().signInWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(this.onLoginFail.bind(this));
});
}
onLoginFail() {
this.setState({ error: 'Authentication Failed.', loading: false });
}
onLoginSuccess() {
this.setState({
email: '',password: '',error: '',loading: false});
}
render
....
value={this.state.email}
onChangeText={email => this.setState({ email })}
/>
</CardSection>
<CardSection>
<Input
...
onChangeText={password => this.setState({ password })}
/>
Try to catch the error and console.log it.
onButtonPress() {
const { email, password } = this.state;
this.setState({ error: '', loading: true });
firebase.auth().signInWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch((error) => { <===
console.log(error); <===
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(this.onLoginFail.bind(this));
});
}
According to the JS Auth documentation on the Firebase website, it only shows how to get the displayName and how to update displayName. So I tried to update it. But it is sort of not logical, because how can you update something without creating it.
So my question here is, how can I set displayName of user during registeration?
function createUser(email, password) {
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function (error) {
error.message.replace(".", "");
alert(error.message + " (" + error.code + ")");
document.getElementById("password").value = "";
});
if (firebase.auth().currentUser != null) {
firebase.auth().currentUser.updateProfile({
displayName: document.getElementById("name").value
}).then(function () {
console.log("Updated");
}, function (error) {
console.log("Error happened");
});
}
}
I have already tried this and it has been proven not to work...
Sincerely,
Farouk
You have to chain the request:
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(result) {
return result.user.updateProfile({
displayName: document.getElementById("name").value
})
}).catch(function(error) {
console.log(error);
});`
This is what i used in firebase v9 using async await
// firebase-config.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: ...,
authDomain: ...,
projectId: ...,
storageBucket: ...,
messagingSenderId: ...,
appId: ...,
measurementId: ...,
}
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
// register.js
import { auth } from "../../services/firebase-config";
import {
createUserWithEmailAndPassword,
sendEmailVerification,
updateProfile,
} from "firebase/auth";
// handleRegister
const register = async (name, email, password) => {
try {
await createUserWithEmailAndPassword(auth, email, password).catch((err) =>
console.log(err)
);
await sendEmailVerification(auth.currentUser).catch((err) =>
console.log(err)
);
await updateProfile(auth.currentUser, { displayName: name }).catch(
(err) => console.log(err)
);
} catch (err) {
console.log(err);
}
};
then you just call this function onClick/onSubmit by passing name, email, and password
here's is my implementation using formik onSubmit
onSubmit={({ name, email, password }) => {
register(name, email, password);
}}
or you can simply call the function in button onClick
<button onClick={() => register(name, email, password)}>submit</button>
I couldĀ“t use ({displayName: name}) directly (sintaxe error in editor). Then, I found another way:
UserUpdateInfo updateInfo = UserUpdateInfo();
updateInfo.displayName = name;
result.user.updateProfile(updateInfo);
This is in Dart (I am using Firebase with Flutter).
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then((res) => {
const user = firebase.auth().currentUser;
return user.updateProfile({
displayName: newUser.name
})
})
This worked for me.
you need to import updateProfile from firebase/auth
import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
updateProfile(auth.currentUser, {
displayName: "Jane Q. User", photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
// Profile updated!
// ...
}).catch((error) => {
// An error occurred
// ...
});
working for me
source: https://firebase.google.com/docs/auth/web/manage-users#update_a_users_profile