Reputation: 1659
I have a function that takes user's input and search through firebase database. What I want to do is catch the any error most especially when their is no match for the user input I want to display as something like "No match was found for the number entered".
this is the function I'm using
function searchNSN(data){
var container = document.getElementById('searchresult');
container.innerHTML = '';
var FindNSN = document.getElementById('searchinput').value;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var BusinessesId = firebase.auth().currentUser.uid;
return database.ref('/Businesses/' + BusinessesId + '/Inventory/' + FindNSN).once('value').then(function(snapshot) {
var Results = snapshot.val();
var Productkey = Object.keys(snapshot.val())[0];
var ResultCard = `
<h1 class="searchtitle first">${Results.ProductName}</h1>
<p class="searchtext">${Results.ProductDescription}<span class="class">${Results.NSN}</span></p>
<p class="showproductdetail" onclick="SHOWSEARCHDETAIL();"><a href> Show Product Details </a href></p>
`
container.innerHTML += ResultCard;
});
}
})
}
I know the console logs the error but how do I implement catching the error and reporting it to the user?
Upvotes: 1
Views: 119
Reputation: 5487
If the database location/reference does not contain any data, it will still trigger a value
event but with an empty DataSnapshot
(i.e. snapshot.val()
is null
). You may check if snapshot.val() === null
, and if it does, let the user know that there are no results.
Reference, the value event section.
Upvotes: 2