Reputation: 101
I am trying to achieve unique username constraint on firestore. I have been experimenting and I couldn't handle it properly. I want to create firebase auth record after making sure username isn't taken, and create firestore record. I first tried to nest then()
(for creating auth record) inside another then()
(username check inside db) but it got very messy. As you can see I am even experimenting with if()
and else
's. I would appreciate if someone gave insights.
export const signUp = (newUser) => {
return (dispatch, getState, {getFirebase, getFirestore}) => {
const firebase = getFirebase();
const firestore = getFirestore();
const user = firestore.collection("users").where("username", "==", newUser.username).get();
if (!user) {
firebase.auth().createUserWithEmailAndPassword(
newUser.email,
newUser.password
).then((response) => {
return firestore.collection("users").doc(response.user.uid).set({
firstName: newUser.firstName,
lastName: newUser.lastName,
username: newUser.username,
createdAt: new Date()
})
}).then(() => {
dispatch({type: "SIGNUP_SUCCESS"});
}).catch((err) => {
dispatch({type: "SIGNUP_ERROR", err});
});
} else {
dispatch({type: "SIGNUP_ERROR", err: {message: "username taken"}});
}
}
};
Upvotes: 0
Views: 186
Reputation: 101
Found a way to handle unique usernames by checking "users" collection in firestore.
export const signUp = (newUser) => {
return (dispatch, getState, {getFirebase, getFirestore}) => {
const firebase = getFirebase();
const firestore = getFirestore();
let exists = null;
let message = null;
firestore.collection("users")
.where("username", "==", newUser.username)
.get()
.then((snapshot) => {
if (!snapshot.empty) {
exists = true;
message = "Username you chose is unavailable";
}
})
.then(() => {
if (!exists) {
return firebase.auth().createUserWithEmailAndPassword(
newUser.email,
newUser.password
);
}
}).then((response) => {
return firestore.collection("users").doc(response.user.uid).set({
firstName: newUser.firstName,
lastName: newUser.lastName,
username: newUser.username,
createdAt: new Date()
})
}).then(() => {
dispatch({type: "SIGNUP_SUCCESS"});
}).catch((err) => {
if (message) {
dispatch({type: "SIGNUP_ERROR", err: {message}});
message = null;
} else {
dispatch({type: "SIGNUP_ERROR", err});
}
});
}
};
Upvotes: 1