J.lan
J.lan

Reputation: 223

save data with custom keys firebase react native

databaseReference:

example of problem

Im trying to save data to my firebase realtime database and I need my key to be the users ID and not the random generated unique key I tried child but still got some random keys any help? this is the method I currently have

async componentWillMount() {


const {data} = await Contacts.getContactsAsync({
  fields: [Contacts.Fields.PhoneNumbers],
});

this.setState({dataSource: data.map(contact => ({...contact, key: contact.number}))});

const contacts = data.filter(d => d.phoneNumbers);

contactsToUpload.forEach(contact => {
  const number = contact.phoneNumbers[0].number.replace(/\D/g, '');
  const ref = firebase.database().ref('/Contacts/' + number);
  try {
    ref.push(contact.name);
  } catch (error) {
    console.log(error);
  }
});
}
//Currently have
"Contacts" : {
  "5554787672" : {
    "-LWIlxwIETK5UR3O5GkR" : "Daniel Higgins Jr.",
    "-LWImsOurEVDOE-KrkVw" : "Daniel From School"
 }
//Needed
"Contacts" : {
 "5554787672" : {
  "UserId1" : "Daniel Higgins Jr.",
  "UserId2" : "Daniel From School"
 }

Upvotes: 0

Views: 2131

Answers (2)

Nkoro Joseph Ahamefula
Nkoro Joseph Ahamefula

Reputation: 530

db.ref('UsersList/').child('name you want to use').set({
    email:this.state.email,
    fname: this.state.lastname,
    lname: this.state.firstname,
}).then((data)=>{
    //success callback
    alert('success'+data);
}).catch((error)=>{
    //error callback
    alert('failed'+error);
  })

something like this worked for me and I was able to store based on special usernames I needed.

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598837

Every time you call push() Firebase generates a reference to a new, unique location in the database. So ref.push() creates a new, unique location under ref.

If you want to simply set the name under the contact's ID, change ref.push(contact.name); to:

ref.set(contact.name);

Upvotes: 0

Related Questions