Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

430
Visualizações
How do I link each user to their data in Firebase?

I plan to create a main tree named users which will include the name different users used as username. So, from each username will be included their data e.g. Full Name, Address, Phone No.

I want to know how to get each user's data when they log in on their profile.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

First of all i suggest you spend some time getting familiar with firebase by reading the Firebase Guide (Link to old Firebase Guide). Everything you need to know to answer your own question is available there. But for simplicity i will put an example here:

Lets start with security, here are the basic firebase rules you need for this example: (source: Understanding Security) (old source: Understanding Security)

{
  "rules": {
    "users": {
      "$user_id": {
        ".write": "$user_id === auth.uid"
      }
    }
  }
}

I will skip the actual user creation and logging in and focus on the question about storing and retrieving user data.

Storing data: (source: Firebase Authentication) (old source: User Authentication)

// Get a reference to the database service
var database = firebase.database();
// save the user's profile into Firebase so we can list users,
// use them in Security and Firebase Rules, and show profiles
function writeUserData(userId, name, email, imageUrl) {
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email
    //some more user data
  });
}

The resulting firebase data will look like this:

{
  "users": {
    "simplelogin:213": {
      "username": "password",
      "email": "bobtony"
    },
    "twitter:123": {
      "username": "twitter",
      "email": "Andrew Lee"
    },
    "facebook:456": {
      "username": "facebook",
      "email": "James Tamplin"
    }
  }
}

And last but not least the retreiving of the data, this can be done in several ways but for this example i'm gonna use a simple example from the firebase guide: (source: Read and Write data) (old source: Retreiving Data)

//Get the current userID
var userId = firebase.auth().currentUser.uid;
//Get the user data
return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
    //Do something with your user data located in snapshot
});

EDIT: Added example of return data

So when you are logged in as user twitter:123 you will get a reference to the location based on your user id and will get this data:

"twitter:123": {
          "username": "twitter",
          "email": "Andrew Lee"
        }
over 4 years ago · Santiago Trujillo Relatório

0

Though I agree with Andre about setting the rules for good security - I would handle the data a bit differently. Instead of generating the string I use the child() method. It's a matter of personal preference.

Get the UID and define a data object:

let user = firebase.auth().currentUser
let uid = user.uid
let yourdata = { foo: 'something', bar: 'other'}

Save the data:

firebase.database().ref('users').child(uid).set(yourdata)
    .then((data) => {
        console.log('Saved Data', data)
    })
    .catch((error) => {
        console.log('Storing Error', error)
    })    

Fetch the data:

firebase.database().ref('users').child(uid).once('value')
    .then((data) => {
        let fetchedData = data.val()
        console.log('Fetched Data', fetchedData)
    })
    .catch((error) => {
        console.log('Fetching Error', error)
    })    

Please notice that set() will override your data so you might want to use push() later on.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda