I am trying to check whether a specific productID and orderID is in my database.
Currently, I am calling and fetching the data from my database like so.
const { data } = useFetchCollection("returns");
const filteredReturns = data.filter((mapper) => mapper.userID === userID);
const idReturns = filteredReturns.flatMap((mapper) => {
const getOrderID = mapper.orderID;
const getProductID = mapper.productID;
return [getOrderID, getProductID];
});
The data is being called and I am getting this array back:
['xxy6mkDDIhXQbUcol1Vh', '6RpJmOYLcGOkyAW4ElP9', 'JIzCbmOqp5wCGz7pHGSL', '6RpJmOYLcGOkyAW4ElP9']
I also have the orderID and productID from the user, these pieces of data will be in the database if a user has submitted a return and not in the database if the user has not submitted a return. So in other words it may or may not be in the database.
The orderID and the productID which is specific to the user is in this format for example,
userDetails[0].id = 6RpJmOYLcGOkyAW4ElP9
id = JIzCbmOqp5wCGz7pHGSL
I now want to check whether this data is in the database.
const mapData = idReturns.map((mapper) => {
if(mapper.orderID === userDetails[0].id && mapper.productID === id){
return true
}else {
return false
}
});
I have been using the function above but it doesn't seem to work. It doesn't say true or false properly. Notably, it only says true, false rather than definitively just true true.
I think my approach with my function is poor. I may even be making a mistake by doing this,
return [getOrderID, getProductID]~
but I am open to suggestions and advice.
Thanks in advance!
use findIndex() instead of map()
if(idReturns.findIndex((mapper)=>mapper.orderID === userDetails[0].id && mapper.productID === id) !=-1) {
return true
}else{
return false
}
Related
I have a query to firebase where i get all products, but i need to add a condition to show products from that type only if the type is different of empty string
this is the static query that is working
this.recordsCollection = this.db.collection('products', ref => {
return ref.orderBy('date_created')
.startAfter(start_after)
.where('type','==','electronics')
.limit(per_p)
});
now this is what i tried and is not working, type_val is the variable, only include the where if is different of empty value, but i get error
this.recordsCollection = this.db.collection('products', ref => {
return ref.orderBy('date_created')
.startAfter(start_after)
if(type_val != ""){ .where('type','==',type_val) }
.limit(per_p)
});
also i tried this, and there is error
ref = ref.orderBy('date_created')
ref = ref.startAfter(start_after)
if(type_val != ""){ ref = ref.where('type','==',type_val) }
ref = ref.limit(per_p)
You can try this:
let query = ref.orderBy('date_created').startAfter(start_after)
if (type_val != "") {
query = query.where('type','==',type_val)
}
The where method too returns a query
I am new to programming.
I have a firebase realtime database. My intent is to get data from the realtime database when a condition is met. That means using a loop statement.
Here is the code:
function firestore(agent) {
var firebaseEntity = agent.parameters.firebase;
return admin.database().ref('questions').once("value").then((snapshot) => {
var questionList = snapshot.child("Entity").val();
for (const i in questionList) {
if (questionList[i].entity == firebaseEntity);
var response = questionList[i].response;
agent.add(`${response}`);
}
});
}
I want to return 'response' when the user's input matches the 'question' column:
There are a few problems with your code:
There is no Entity node under /questions, so your questionList will always be empty.
There is not even an Entity node under each individual question, as it's called entity with a lowercase e.
I recommend using Firebase's built-in forEach function to iterate over the child nodes, instead of for... in.
So with those:
function firestore(agent) {
var firebaseEntity = agent.parameters.firebase;
return admin.database().ref('questions').once("value").then((snapshot) => {
snapshot.forEach((questionSnapshot) => {
let question = questionSnapshot.val();
if (question.entity == firebaseEntity) {
cont response = question.response;
agent.add(`${response}`);
}
});
});
}
I have a project on pure javascript,and I was working on saving items to localstorage. I only need to save id, name and image of the item i am saving.
My major problem , however is i do not want save duplicate .Therefore before i save i must check whether the exists or not.
I have so far tried several approaches but all seems not to work.Below is my code snippets.
I am able to save item to localstorage with no problems, infact i can save and delete items from localstorage correctly.
const cart_DB = new cartDB();
if( cart_DB.isAddedToCart(cartInfo.id) === false) {
// save item to database
}else {
alert('item already in cart');
return false;
}
class cartDB {
/// save cart into localstorage ////
saveIntoDB(cart) {
const carts = this.getFromDB();
carts.push(cart);
// add the new array into localstorage
localStorage.setItem('carts', JSON.stringify(carts));
}
/// save cart into localstorage ///
/// return carts from storage ///
getFromDB() {
let carts;
// check from local storage
if (localStorage.getItem('carts') === null) {
carts = [];
} else {
carts = JSON.parse(localStorage.getItem('carts'))
}
return carts;
}
/// carts from storage ends ///
/// check if item already exists in database ////////
isAddedToCart(id) {
if (localStorage.getItem(id) === null
||localStorage.getItem(id).length === 0) {
return false;
}else {
return true;
}
}
//// checking items ends here ///////
}
What i want is to check whether the item exists or not before adding another item.
Assuming that you store items in array you can use below function to check if item already exists:
function checkIfItemExists (id) {
const items = localStorage.getItem('carts')
let itemExists = false
if (items) {
const itemsData = JSON.parse(items)
// check if item with given id exists in local storage data
itemExists = itemsData.find(item => item.id === id)
}
return itemExists
}
If your goal is to find out if there's a duplicate, Array.some() would be the best function you are looking for. Implement it to your function like this.
isAddedToCart(id) {
const carts = localStorage.getItem('carts');
return carts.some(cart => cart.id == id);
}
Array.some() Definition and Usage
The some() method checks if any of the elements in an array pass a
test (provided as a function).
The some() method executes the function once for each element present
in the array:
If it finds an array element where the function returns a true value, some() returns true (and does not check the remaining
values)
Otherwise it returns false
I have a complex multi-select filter page so I'm grouping filters like this http://localhost:3000/search?id[]=101404&id[]=7267261. I'm using URLSearchParams() to manage my URLs.
The only thing that is not working is removing a parameter once it has been unchecked. I tried using the URLSearchParams.delete(), but it only accepts a single parameter, name. If I pass id[], it removes ALL id[]'s, not just the one I want to be deleted.
EDIT: based on recommendations, I have this new code (see old code below). Hoping someone has a far more elegant solution.
setQueryParams = (param = null, value = null, category = null) => {
....
// parameter exists but value is false
} else if (param && !value) {
// find all values for category and filter out unchecked value
const values = params.getAll(`${category}[]`).filter(category => category !== param)
// remove entire category from URLSearchParams
params.delete(`${category}[]`)
// loop over filtered list and append them BACK to URLSearchParams
values.forEach((value) => {
params.append(`${category}[]`, value)
});
}
this.setState({
query: params.toString()
});
}
The only other way I can think of is to write some Regexp, which I wasn't able to get it to work anyway. My params are encoded, so shouldn't something like this work? I can't even get this to work in console...
"id%5B%5D=101404&id%5B%5D=7267261".replace(/\%5\%D/,'')
"id%5B%5D=101404&id%5B%5D=7267261".replace(/%5%D/,'')
"id%5B%5D=101404&id%5B%5D=7267261".replace(/\[\]/,'')
None of these work. Here is my code generating the query parameters.
setQueryParams = (param = null, value = null, category = null) => {
const query = this.state.query;
// get current location
const location = this.props.location.search;
// Set params based on whether component mount or filter change
const params = param ? new URLSearchParams(query) : new URLSearchParams(location);
// value must be equal to true
if (param && value) {
params.append(`${category}[]`, param);
// parameter exists but value is false
} else if (param && !value) {
params.delete(category);
}
this.setState({
query: params.toString()
});
}
What if you use the getAll('id[]'), iterate over the results and append() the ones you want.
Although it's not that elegant of a solution, I think it's still better than the regex approach.
setQueryParams = (param = null, value = null, category = null) => {
....
// parameter exists but value is false
} else if (param && !value) {
// find all values for category and filter out unchecked value
const values = params.getAll(`${category}[]`).filter(category => category !== param)
// remove entire category from URLSearchParams
params.delete(`${category}[]`)
// loop over filtered list and append them BACK to URLSearchParams
values.forEach((value) => {
params.append(`${category}[]`, value)
});
}
this.setState({
query: params.toString()
});
}
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.