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?
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.
Related
function AddDocument(Name, TTid) {
auth.onAuthStateChanged(user => {
if(user) {
const colUser = collection(fsinfo, 'User');
// goes to database colelction "user"
const colUser2 = doc(colUser, user.uid);
// goes to the document in colUser named "one"
const colUser3 = collection(colUser2, 'MoviesLiked');
whenSignedIn.hidden = false;
whenSignedOut.hidden = true;
setDoc(doc(colUser3, Name), {
movieliked: TTid,
})
}
else {
whenSignedIn.hidden = true;
whenSignedOut.hidden = false;
//userDetails.innerHTML = '';
console.log( "while logged out" );
console.log("notloggedin");
}
})
};
// query can either be a title or a tt id
function searchMovie(query) {
const url = `https://imdb8.p.rapidapi.com/auto-complete?q=${query}`;
fetch(url, options)
.then(response => response.json())
.then(data => {
var outname = null;
var outdetail = null;
const movieList = document.querySelector('.movielist');
movieList.addEventListener('click', handleClick);
const list = data.d;
//array of list with data from the movie search
//data.d is the specific datas that is outputted from the api
//list is an array that holds that data
console.log(list)
// ^ will output what list holds
const html = list.map(obj => {
const name = obj.l; // holds the name of movie
outname = name;
const poster = obj.i.imageUrl; // holds the poster, i is the image
const detail = obj.id
outdetail = detail;
return `
<section class="movie">
<img src="${poster}"
width = "500"
height = "800"/>
<h2>${name}</h2>
<section class = "details">${detail}</section>
<button type="button">Movie Details</button>
</section>
`;
}).join('');
// Insert that HTML on to the movie list element
function handleClick(e) {
if (e.target.matches('button')) {
const details = e.target.previousElementSibling;
details.classList.toggle('show');
AddDocument(outname, outdetail);
}
}
movieList.insertAdjacentHTML('beforeend', html);
document.getElementById("errorMessage").innerHTML = "";
})
.catch((error) => {
document.getElementById("errorMessage").innerHTML = error;
});
I have a function that will take search to an API call and then load the info from the API to a list.
It should then output said each of said list using list.map(obj) and each item will have a name, poster, and a button attached to it.
Outside the map I have a function that will react when the button is pressed which will toggle and then load the details of the movie to a database in the AddDocument function. My issue is that I am not sure how to make it so that when the button is pressed AddDocument will add whichever obj.name is connected to the button.
Currently, AddDocument will only add the last item in the list and not the item that I pressed the button for.
I know that it is because the function is outside where the mapping is done, and thus the items that are held in outname, and outdetail are the last items that have been mapped. But I just can't figure out a way to make the button press add the correct document to the database.
(I really didn't want to ask this, but I had spent hours thinking and searching and couldn't seem to find a solution. Thank you for any form of feedback that there may be.)
I am trying to find a way to find the value of the id given the email.
For example, If I had email2#gmail.com, It would give me the ID 108454568498950432898.
All emails are unique and there will be no repetition of emails.
This is my user tree:
Note: In the image it says email2 instead of email2#gmail.com. Ignore this
Here's my code so far:
(Code won't run obviously but it's easier to enter code using the embed)
var users;
var givenEmail = "email2#gmail.com";
var neededID;
var dataRef = firebase.database().ref('users');
dataRef.on('value', (snapshot) => {
const data = snapshot.val();
users = data;
});
var usersArray = Object.keys(users);
for(i = 0; i < usersArray.length; i++) {
if(users[i].email == givenEmail) {
neededID = i;
break;
}
}
I recommend using a query to perform the filtering on the server, instead of downloading the entire users node and filtering in your application code as you now do.
var givenEmail = "email2#gmail.com";
var dataRef = firebase.database().ref('users');
var query = dataRef.orderByChild('email').equalTo(givenEmail);
dataRef.once('value', (snapshot) => {
snapshot.forEach((userSnapshot) => {
console.log(userSnapshot.val().id);
});
});
Well, I think you are almost there.
users[i].email
you can retrieve the email using this method, and similarly you can do it with id too
users[i].id
Please note that you wanted to find email2#gmail.com but your firebase only have email2
Maybe you would want to change that
Im working on a Coronavirus application. And im using this API: https://api.covid19api.com/live/country/south-africa
In my application a user is supposed to type the name of any given country and it should display the numbers of deaths, confirmed cases, recovered people. I keep getting a 404 error.
HTML & CSS can be found here:
https://github.com/Kazim786/coronavirus-updates/blob/master/index.html
https://github.com/Kazim786/coronavirus-updates/blob/master/style.css
(havent done much styling yet)
Here is my Javascript code:
// The api: https://api.covid19api.com/live/country/south-africa
// const theCountries = await axios.get(`https://api.covid19api.com/live/country/south-africa`)
// console.log(theCountries.data[0].Confirmed)
// console.log(theCountries.data[0].Deaths)
// console.log(theCountries.data[0].Recovered)
const countries = document.getElementById('countries').value
const results = document.getElementsByClassName('results')
const submitBtn = document.getElementById('submit')
const data = []
console.log(countries)
//Async Function
//`https://api.covid19api.com/live/country/${countries}`
console.log(byCountries())
async function byCountries(){
try {
const theCountries = await axios.get(`https://api.covid19api.com/live/country/${countries}`)
const deaths = theCountries.data[0].Deaths
const confirmed = theCountries.data[0].Confirmed
const recovered = theCountries.data[0].Recovered
data.push(deaths, confirmed, recovered)
console.log(theCountries)
await console.log(data)
}
catch{
console.log("Error");
}
}
//Show results function:
function showResults(){
if (countries !== null){
results.innerHTML = `${countries} has number of deaths, confirmed cases, recovery as the following: ${data}. `
} else {
results.innerHTML = 'Enter a name of a Valid Country'
}
}
//Add Event Listener
submitBtn.addEventListener('click', showResults)
You're trying to get the result while the input field is empty as js loads.
You can make the submit button call both byCountries() and showResults(), and you'll also need to fetch the value inside byCountries()
submitBtn.addEventListener('click', () => {
byCountries()
showResults()
})
async function byCountries(){
try {
const countries = document.getElementById('countries').value
const theCountries = await axios.get(`https://api.covid19api.com/live/country/${countries}`)
...
I am having trouble removing data from my database on Firebase. I am able to remove data but when I remove the data its removing all my users? I only wanted it to remove the user represented in the user ID.
My JS
function removeUser(userID){
var userRef = firebase.database().ref('users/');
// Returned no user found
//var userRef = firebase.database().ref('users/').child('userID');
// Returned reference child error
//var userRef = firebase.database().ref('users/').child(userID);
userRef.once('value', function(snapshot) {
if (snapshot.val() === null) {
alert("no user found");
}else{
userRef.ref.remove();
}
});
console.log('Remove Success');
}
document.getElementById('removeUserBtn').addEventListener('click', function(){
removeUser(userID);
});
You need to specify the full path to the child you are trying to remove:
var childUserRef = firebase.database().ref(`users/${userId}`)
and call the .remove() method as in : childUserRef.remove()
More details:
https://firebase.google.com/docs/reference/js/firebase.database.Reference
I am building an app with Vue and also Firebase. I am new to Firebase and i've some problems with it. I try to store names + emails in the database. What I want is to check first if the email is already in the database and if not, run another function that will store the name + email. If the email is stored in the database I would like to output an alert and cancel the submit.
So the check of the email in the database is going quite well, it will output an alert, and also I am able to retrieve the data. But where the problem lays is that when I enter an email that is not in the database. When I enter a new email (and name) it will check the database and return false but then right away does another call (I dont know why, that's the problem I guess) and it will return true, and the alert of already being there, at the same time. Then it will proceed to another function to store the data because that was the output of the first call (which was false).
My JS code:
checkForm() {
let app = this;
if (this.name == '' || this.emailadress == '') {
alert('You have to fill out the form');
} else {
app.getFirebase();
}
},
getFirebase() {
let app = this;
var ref = firebase.database().ref().child('/aanmeldingen/');
ref.on('value', function(snapshot) {
const array = [];
snapshot.forEach(function(childSnapshot) {
var checkEmail = childSnapshot.val().email;
array.push(checkEmail);
});
const res = array.includes(app.emailadress);
console.log(array);
console.log(res);
if(res) {
alert('You already have entered the giveaway');
} else if (res == false) {
app.store();
}
});
},
store() {
this.step_two = false;
this.active_two = false;
this.active_three = true;
this.step_three = true;
let app = this;
firebase.database().ref('/aanmeldingen/').push({
username: app.name,
email: app.emailadress,
});
}
Screenshot of console (entered Jane, not in the database)
You should be using once() instead of on(). on() leaves the listener attached, so when you push data in store() the listener fires again.