Adding user information to firebase (signup) react native

Viewed 28
createUserWithEmailAndPassword(auth, state.email, state.password)
        .then((userCredential) => {
          setDoc(doc(db, "users", userCredential.user.uid), {
            firstName: state.firstName,
            lastName: state.lastName,
            email: state.email,
            address: state.address,
            username: state.firstName,
          })

Hi, im trying to add username in firebase user collection. Username should be firstname.lastname but I dont know how should I type that. This is currently working perfect but I just want add in username field "Lastname" but dont know how

1 Answers

You are on the right track. You just need to join the first and last names together.

You can use + as strings can be added or use string interpolation (which is more elegant).

// adding strings 
const username = state.firstName + '.' + state.lastName;

// using string interpolation.
// here, you use the backtick character (`), it is usually found below escape.
// then use ${variable} to interpolate variable.
const username = `${state.firstName}.${state.lastName}`;

So your final code could look like the following. I formatted it and used async/await (because setDoc returns a promise). I also made the code more elegant with object destructuring.

createUserWithEmailAndPassword(auth, state.email, state.password) 
 .then(async (userCredential) => {
    const { address, email, firstName, lastName } = state;
    const username = `${firstName}.${lastName}`;
    await setDoc(
      doc(db, 'users', userCredential.user.uid), 
      { address, email, firstName, lastName, username },
    );
 });
Related