How can I retrieve data from firebase database by its value in Web App? - javascript

I am making a complaint portal and I want to assign id to the people who register.
My data structure in firebase like below:
fir-web-learn-51ffc
complaint
-Kwe6QXol8DV-uMDxIe7:"Hiii"
-KweCaYQrgG75BiJW3dA:"Hooooo"
and I have used this code for insertion:
function submitClick()
{
var complaint=document.getElementById('complaint').value;
var database=firebase.database().ref().child("complaint");
database.push().set(complaint);
}
for the above code, How can I retrieve the Name(Kwe6QXol8DV-uMDxIe7) by its value(Hiii). I have tried the code given on Google Firebase Documentation and Youtube but didn't work.

You'll use a Firebase query for that with orderByValue. So something like this:
var ref=firebase.database().ref().child("complaint");
ref.orderByValue().equalTo("Hiii").once("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key);
});
});
Aside from the query itself, the main thing to note is the snapshot.forEach() in the callback. This loop is needed since a query can potentially match multiple results.

Related

How to retrieve a specific data from Firebase

I am designing a website where when the user comes and enters his email id, a corresponding value gets printed on the website.
I have the below data on my real-time firebase database.
How do I write a javascript function in my JS file so that when a user enters his/her email-id, the value of the total gets printed on the website?
I have tried something like this:
function getdata(){
var email=document.getElementById("email").value;
firebase.database().ref('0/'+email).once('value').then(function(snapshort){
var total=snapshort.val().total;
document.getElementById("total").innerHTML=total;
})}
I think you're trying to perform a query based on the email property of the node.
In that case, it'd be:
firebase.database().ref()
.orderByChild("email")
.equalTo(email)
.once('value').then((results) => {
results.forEach((snapshot) => {
let total = snapshot.val().total;
document.getElementById("total").innerHTML=total;
});
});
I recommend reading the Firebase Realtime Database documentation end-to-end, as it should answer many of the questions you may have about the API. A few hours spent there now, will save you many hours down the line.

Search for artist id by name

I am delving into spotify and javascript is not my main programming language so I managed to get some snippets together from a code that uses ajax (which I would rather not use) but still it returns nothing so I am wondering if some more experienced people out there could help me get started with a template to call the api.
My goal for this test is to search an artist name and get the first result (I expect many names will return multiple artists)
Most of what is in the documentation is curl and I didn't find the demos very helpful.
What I have so far is something like this:
function getArtistName (artistName) {
var artistID;
var searchArtists = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: query,
type: 'artist',
'accessToken': 'BQBvW70gHJ20Flc8cHErqg8s72bfTePbssblED-gpEuHFr_Yezesbthok8qaKBmjzo2WjWo9J7ZcTpSwvV8MZ_cW_E7UkrG_HF2R6gFQcqfdupgYGmoYsdRdt1q3tq2NU3pPgauuzmFLkUpdAuNp3shdVXJz2SzvnA',
'query': artistName,
limit: '1.'
},
success: function (response) {
//resultsPlaceholder.innerHTML = template(response);
}
});
};
console.log(searchArtists);
return artistID;
}
Some points of confusion:
The key seems to expire. I have a client ID on my profile but I am not sure where I can generate this token other than the "try it out" demo on the site.
What does this actually return, an ID or a JSON?
Here is a demo app that searches tracks using Node.js, or server-side Javascript: https://spotify-quicksearch.glitch.me/
If you click the "Remix this on Glitch" link on the page, you can see and edit the source.
The call to the API is made in server.js. First, we set the client ID and client secret, which are from the dashboard, as you've noted. In this example, we use those to get an access token using the Client Credentials Flow. You can read about all the authentication flows here: https://beta.developer.spotify.com/documentation/general/guides/authorization-guide/
This particular example uses an API wrapper called spotify-web-api-node, which just makes it easier to interact with the API through Javascript functions. To search for artists instead, just change searchTracks to searchArtists.
To answer your second question - all calls to the Spotify API return JSON. You can see the format of the full JSON response here: https://beta.developer.spotify.com/documentation/web-api/reference/search/search/. Roughly, it looks like this:
artists: {
items: [
{
id: <id>,
name: <name>,
...
}
...
]
}
To get the ID from the JSON, you need to parse the JSON object. You can see how I do this in the example in line 21 of client.js. You can modify that code to get just the ID of the first artist like this:
data.artists.items[0].id
Update: made an example that should be even more relevant:
https://spotify-search-artist.glitch.me/

Querying By Multiple Keys in Firebase

I have a list of known keys in my Firebase database
-Ke1uhoT3gpHR_VsehIv
-Ke8qAECkZC9ygGW3dEJ
-Ke8qMU7OEfUnuXSlhhl
Rather than looping through each of these keys to fetch a snapshot of their respective object, how can I query for each of these keys in one single, unified request? Does Firebase provide this?
I've discovered the Promise.all() function which looks promising (no pun intended I swear) but I'm not sure how to implement it using the standard way of fetching firebase data like so
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
var username = snapshot.val().username;
});
Thanks for any help!
As David's comment suggested: if the items are in some way related, you may be able to built a query to get them all.
Otherwise this would do the trick:
var keys = [
"-Ke1uhoT3gpHR_VsehIv",
"-Ke8qAECkZC9ygGW3dEJ",
"-Ke8qMU7OEfUnuXSlhhl"
];
var promises = keys.map(function(key) {
return firebase.database().ref("/items/").child(key).once("value");
});
Promise.all(promises).then(function(snapshots) {
snapshots.forEach(function(snapshot) {
console.log(snapshot.key+": "+snapshot.val());
});
});
Note that retrieving each item with a separate request is not as slow as you may think, since the requests are all sent over a single connection. For a longer explanation of that, see Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly.

Is "ref.off()" the correct approach to disconnect from Firebase Database after reading data?

We have scenarios where we read data from the Firebase Database and then disconnect (we do not care to receive updates on that data). We use code like the snippet below:
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
// Display the data
});
});
We use ref.once() because we care to read the data all at once, we understand that there's monitoring set on the data nonetheless by Firebase.
What's the best approach to stop the monitoring, and should we even attempt that in an effort to reduce resources consumed, etc.? We tried ref.off() and that didn't seem to make a difference.
As per the official document, you don't need to call off().
In some cases you may want a snapshot of your data without listening for changes, such as when initializing a UI element that you don't expect to change. You can use the once() method to simplify this scenario: it triggers once and then does not trigger again.
This is useful for data that only needs to be loaded once and isn't expected to change frequently or require active listening. For instance, the blogging app in the previous examples uses this method to load a user's profile when they begin authoring a new post:
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});

Need helping retrieving data from Firebase

So I've been using Firebase as a database for my website (this is a web based project, using HTML, CSS and JS) and I'm running into a problem retrieving data from it.
Basically this site allows users to create a profile for a character (they can fill in the name, the characters stats etc...) and when they click submit, it'll save the values they filled out to the database.
The values are saved perfectly fine, but when I go to retrieve the data the command doesn't seem to do anything.
So in order to get the profiles, I've been trying to use this bit of code to get whatever is stored at the specified .ref(path):
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
Which according to the Firebase docs should return a list of keys at the path that I specified in .ref(). However whenever I try to access whatever is in the var, it just gives me the string that contains a link to the database that looks like this:
https://#mydatabaseurlhere.firebaseio.com/users/uid/chars
Where #mydatabaseurlhere is the url I created on the Firebase app, and the uid is the authenticated user's ID.
I've been reading the docs, and its telling me that the above code should return a list of whatever is at the path that I specified, but so far it just gives me a link. Is there something I've been missing from the Docs that'll allow me to access whatever data is currently in the database? Because I've tried to take a snapshot using .once() to no avail either. I've also set the rules on /users/ to allow anyone to read/write to the database but I'm still not able to access the data (or maybe I am accessing, I'm just missing how to retrieve it).
Either way, I'm wondering how one can go about accessing this data, as I'm extremely confused as to why I can't seem to retrieve the data that has been successfully written to the database.
You're defining a query. But that doesn't yet retrieve the data.
To retrieve the data, you need to attach a listener. For example:
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
getChar.on('value', function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key, child.val());
});
});

Categories