Shubham Bisht
Shubham Bisht

Reputation: 687

How to add data in Firebase Database with unique keys and then fetch the data with unique keys?

-LUeq8x-5QaVSXKJdXtz is the key -LUeq8x-5QaVSXKJdXtz is the key

signup = async () => {
    const { email, pass, job, description, name, age } = this.state;
// fetching state variables to use in this function


    try {   
      await firebase.auth().createUserWithEmailAndPassword(email, pass);

      var playersRef = firebase.database().ref("doctorsList/");

//push function adds the data with a unique key
      playersRef.push({
        doctor: {
          name: name,
          age: age,
          job: job,
          description: description
      },
      });
}
catch (error) { console.log(error)  }
}

How do I fetch the data from Firebase database if they have unique keys?

var ref = firebase.database().ref( 'doctorsList/doctor/' );

  ref.on('value', (snapshot) => {
    alert(snapshot.val().name);
 });

When I use alert(snapshot.val().name); it shows me the name from the database but when I try to save data by this.setState({ name: snapshot.val().name }); it doesn't saves. Or how can I save the data at once from database?

Upvotes: 1

Views: 1076

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598765

Tony's answer shows how to get the doctor once you know their key. There are also various scenarios where you may not know the key.

For example, if you know nothing about the doctor you want to read, all you can do is read the information for all doctors:

var ref = firebase.database().ref( 'doctorsList' );

ref.on('value', (snapshot) => {
  snapshot.forEach((doctorSnapshot) => {
    alert(doctorSnapshot.key+": "+doctorSnapshot.val().doctor.name);
  });
});

If you know for example the name of the doctor(s), you can use a query to retrieve the doctor(s) matching that name with:

ref.orderByChild("doctor/name").equalTo("shubham").on('value', (snapshot) => {
  snapshot.forEach((doctorSnapshot) => {
    alert(doctorSnapshot.key);
  });
});

You'll still need snapshot.forEach here, since there may be multiple doctors with a matching name.

If you'd like to change something about each of those doctors, you can update it within the callback with:

ref.orderByChild("doctor/name").equalTo("shubham").on('value', (snapshot) => {
  snapshot.forEach((doctorSnapshot) => {
    doctorSnapshot.ref.child("job").set("doctor");
  });
});

Upvotes: 2

Tony Bui
Tony Bui

Reputation: 1299

If you want to upload with the specific key, change the ref to this:

const key = //your key here;
var playersRef = firebase.database().ref(`doctorsList/${key}`);

And then if you want to fetch the data with a specific key, change to this:

var ref = firebase.database().ref( `doctorsList/${key}`);

  ref.on('value', (snapshot) => {
    alert(snapshot.val().name);
 });

Upvotes: 1

Related Questions