Firebase user.updateProfile({...}) not working in React App

Viewed 6842

So, I have this ReactJS app, there is a user database,

The function for creating the user is this

import { ref, firebaseAuth } from './../Components/config'

export function auth (email, pw) {
  return firebaseAuth().createUserWithEmailAndPassword(email, pw)
    .then(saveUser)
}
export function saveUser (user) {
  return ref.child(`users/${user.uid}/info`)
    .set({
      email: user.email,
      uid: user.uid,
      number: "" //custom
    })
    .then(() => user)
}

as you see the user is made of 3 properties, email, uid, and a custom number property which initially is "",

I have a

changeNumberToNew = (n) =>{
    var user = firebase.auth().currentUser;
      if (user != null) {
          user.updateProfile({
            number: n
          }).then(() => {
            console.log("Number changer");
          }).catch((error) => {
            console.log(error);
          });
      } else {
        console.log("No user")
      }
  };

and a button to call the function

<button onClick={this.changeNumberToNew(4)}>Click to change number</button>

When i click the button the promise is resolver leading to the execution of

console.log("Number changer")

but when I go and look at the firebase database object .. nothing changes, even if a reload and wait still nothing changes

2 Answers

I think the problem here is that you are confusing the user object in your database with the user in your authentication module. They are not the same.

You save a 'copy' of your user to the database when you say the following in the first chunk.

ref.child(`users/${user.uid}/info`)
    .set({
      email: user.email,
      uid: user.uid,
      number: ""
    })

Then in the second chunk of code you try and update the current user in your authentication module. Not good. You should be updating your database, not your authentication module.

var user = firebase.**auth()**.currentUser

if (user != null) {
  user.updateProfile({...})
}

I don't think you can create a custom field on the current User in the authentication module. The updateProfile() is used to update the fields you get by default from the provider, such as email, display name, photoURL etc. You can't create new ones.

You should update the copy of the user in your database and then reference that when you need the value of 'number'.

You change function should probably be more like...

changeNumberToNew = (n) => {
    var user = firebase.auth().currentUser;
    if (user) {
     ref.child(`users/${user.uid}/info`).update({number: n})
     .then(() => console.log("Number changer"))
     .catch(error => console.log(error))
    } else {
      console.log("No user")
    }
}
Related