react native firebase check if user already exisits in real time database - javascript

i need to check if username already exists in real time database then prompt user to select another username. it keep saying not found. I think it because of how my data is nested.
signup.js
const { email, username, password } = this.state;
await firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(async user => {
console.log('Data created', user);
let rootRef = firebase.database().ref()
rootRef.child("users")
.orderByChild("username")
.equalTo(username)
.once("value")
.then(snapshot => {
if (snapshot.exists()) {
let userData = snapshot.val()
console.log(userData)
Alert.alert('username is taken')
return userData;
}else {
console.log('not found')
}
})

You are creating a user, then check if that user exists. Check if the user exists before creating the user.
const { email, username, password } = this.state;
let rootRef = firebase.database().ref();
rootRef
.child('users')
.orderByChild('username')
.equalTo(username)
.once('value')
.then(snapshot => {
if (snapshot.exists()) {
let userData = snapshot.val();
console.log(userData);
Alert.alert('username is taken');
return userData;
} else {
console.log('not found');
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(async user => {
console.log('Data created', user);
});
}
});

Related

Displaying wrong auth error on page - VUEJS, Firebase

Wanting to display error messages when a person has trouble going through the authentication process (wrong password etc). I have a pinia store which has the actions for login etc below.
async loginUser(email, password) {
this.loadingUser = true;
try {
const { user } = await signInWithEmailAndPassword(
auth,
email,
password
);
this.userData = { email: user.email, uid: user.uid };
router.push("/");
} catch (error) {
console.log(error);
this.userData = {};
} finally {
this.loadingUser = false;
}
},
and my login script form component code below.
const email = ref("");
const password = ref("");
const handleSubmit = () => {
if (!email.value || password.value.length < 8) {
alert("Enter");
}
userStore.loginUser(email.value, password.value);
};
how can i display any authentication error on the page to the user? Much appreciated.

post error firebase authentication with react js

i am encountering a problem concerning firebase authentication
so whenever I submit the form the state will get the signup data but it will not send it to my firebase database
utils.js
export const handleUserProfile = async({ userAuth, additionalData }) => {
if (!userAuth) return;
const { uid } = userAuth;
const userRef = firestore.doc(`users/${uid}`);
const snapshot = await userRef.get();
if (!snapshot.exists) {
const { displayName, email } = userAuth;
const timestamp = new Date();
const userRoles = ['user'];
try {
await userRef.set({
displayName,
email,
createdDate: timestamp,
userRoles,
...additionalData
});
} catch (err) {
console.log(err);
}
}
return userRef;
};
in Signup.js :
handleSubmit = async event => {
event.preventDefault();
const { displayName, email, password, confirmPassword } = this.state;
if (password !== confirmPassword) {
const err = ['Password Don\'t match'];
this.setState({ errors: err })
return
}
try {
const { user } = await auth.createUserWithEmailAndPassword(email, password);
await handleUserProfile(user, { displayName })
this.setState({
...initialState
})
}
catch (err) {
}
}
where i am missing ?

want to create a subcollection in document in firebase when user sign up to app in react native its children subcollection created

want to add a subcollection when the user signs up to the app a subcollection is created to its document which contains its children.
here is my code:
try {
await firebase.auth().createUserWithEmailAndPassword(email, password);
const currentUser = firebase.auth().currentUser;
const db = firebase.firestore();
db.collection("users")
.doc(currentUser.uid)
.set({
email: currentUser.email,
lastName: lastName,
firstName: firstName,
}).collection('users').doc(currentUser.uid).collection("recipient").add({name:"test", age:"25" }).then((data) => {
console.log(data.id);
console.log("Document has added")
}).catch((err) => {
console.log(err)
})
} catch (err) {
alert("There is something wrong!!!!" + err.message.toString());
}
}
The problem in your code is linked second add document to sub-collection because the first promise does not return the document reference but a sort of information about how long operation was taken. The right approach will be the following:
async function addUser(id, user) {
const db = firebase.firestore();
const users = db.collection('users')
try {
const result = await users.doc(id).set(user)
return result
} catch (e) {
console.log("addUser: ", e)
return null
}
}
async function getUserRef(id) {
const db = firebase.firestore();
const users = db.collection('users')
try {
const docSnapshot = await users.doc(id).get()
return docSnapshot.ref
} catch (e) {
console.log("getUserRef: ", e)
return null
}
}
try {
const user = {
email: currentUser.email,
lastName: lastName,
firstName: firstName,
}
const result = await addUser(id, user);
const ref = await getUserRef(id)
await ref.collection("recipient").add({name:"test", age:"25" })
} catch (e) {
console.log(e)
}

I want to check if a user is signed in with firebase

I have an React app with authentication and a firebase backend.
How do i check if the user is signed in? I tried it with onAuthStateChanged. But it only returns:
Here is my code:
import * as FirestoreService from '../../firebase/firebase';
useEffect(() => {
let user = FirestoreService.isLoggedIn()
console.log( user)
}, []);
Now in the firebase file:
export const isLoggedIn = () => {
return firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log("User signed in");
}
else {
console.log("User signed out");
}
});
}
My Check if Loggin was successfull:
function handleLogin() {
FirestoreService.LoggIn(email, password).then(function (result) {
// result.user.tenantId should be ‘TENANT_PROJECT_ID’.
setloggedIn(true)
}).catch(function (error) {
setloggedIn(false);
});
}
Firebase File:
export const LoggIn = (email, password) => {
return firebase.auth().signInWithEmailAndPassword(email, password)
.then(function (result) {
// result.user.tenantId should be ‘TENANT_PROJECT_ID’.
return result;
})
.catch(function (error) {
return error
});
}
onAuthStateChanged() adds an observer for changes to the user's sign-in state but does not return a user object.
In your case you should use the currentUser property. If a user isn't signed in, currentUser is null:
export const isLoggedIn = () => {
return firebase.auth().currentUser;
}

Firebase emailVerified variable isn't changing after clicking the confirmation email

I am using firebase with ReactJS, after creating a user I am sending a confirmation email, after clicking the link, the variable emailVerified remains false no matter what I try.
Here's the code where I create the user and send the email:
const createUserWithEmailAndPasswordHandler = async (event, email, password) => {
event.preventDefault();
try{
const {user} = await auth.createUserWithEmailAndPassword(email, password);
user.sendEmailVerification().then(function() {
user.reload()
}).catch(function(error) {
console.log(error);
});
generateUserDocument(user, {displayName});
}
catch(error){
setError('Error Signing up with email and password');
}
}
And this is the generateDocument code:
export const generateUserDocument = async (user, additionalData) => {
if (!user) return;
const userRef = firestore.doc(`users/${user.uid}`);
const snapshot = await userRef.get();
if (!snapshot.exists) {
const { email,emailVerified, displayName, photoURL } = user;
try {
await userRef.set({
displayName,
email,
emailVerified,
photoURL,
...additionalData
});
} catch (error) {
console.error("Error creating user document", error);
}
}
return getUserDocument(user.uid);
};
Even if I logout and login, refresh the page, it still doesn't change to true.
Thanks for any help!

Categories