I am getting the value of id and quantity during the click button. I want add a new array inside the object array. Below is the code
adddata =(d,v) => {
const product = [];
for (let i = 0; i < 1; i++) {
product.push({
product_id:d,
cart_quantity:v
});
}
console.log(product);
<button value={this.state.quantity} className="btn" onClick={adddata} data-id={item.product_id}>Add to cart</button>
The only issue with this implementation is that. it replacing the new value with an existing one. I want to merge it dynamically every time click on the button.
Please help
You defined the variable product inside the function, So each time when you execute the function, It will be reinitialized.
Use Global Variable / State
// global
const product = [];
addData =(d,v) => {
// I removed the loop because it's useless here.
product.push({
product_id:d,
cart_quantity:v
});
}
Related
my problem is that in my if and else if condition of the for loop the first condition is triggered if we add the second same product contained in the table but when the color condition of the product changes and that lid and the same it triggers me two conditions for the click on the product. What to do ?
I would like to add a quantity ++ if the object and already in the table if the id and the color selected in the input are the same.
otherwise you add a new object in the table.
After the problem is that it adds both the quantity in the product and the quantity in the object here is my code and some screenshot of the console below
produitData = product choice on the page of product
produitTableau = Array an objects save in the localStorage
select = the input contained the varnish value
const addBasket = () => {
let bouton = document.getElementById(produitData._id);
bouton.addEventListener("click", () => {
let produitTableau = JSON.parse(localStorage.getItem("produit"));
let select = document.getElementById("vernis");
const fusionProduitTeinte = Object.assign({}, produitData, {
teinte: `${select.value}`,
quantite: 1,
});
if (produitTableau == null) {
produitTableau = [];
produitTableau.push(fusionProduitTeinte);
localStorage.setItem("produit", JSON.stringify(produitTableau));
} else {
for (i = 0; i < produitTableau.length; i++) {
if (
produitTableau[i]._id == produitData._id &&
produitTableau[i].teinte == select.value
) {
produitTableau[i].quantite++;
console.log("quantite ++");
localStorage.setItem("produit", JSON.stringify(produitTableau));
} else {
console.log("nouveau");
produitTableau.push(fusionProduitTeinte);
localStorage.setItem("produit", JSON.stringify(produitTableau));
}
}
}
console.log(select.value);
console.log(produitTableau);
// window.location = "panier.html";
});
return;
};
one click one object add to array
second click quantity++ add in object to the array it's work the fisrt conditions
enter image description here
third click quantity++ add in object to the array it's work the fisrt conditions
enter image description here
four click im changed the select value
but the product id is the same as in the object in the table quantity++ add in object to the array and new object for the same time it's not work conditions and continue to add new object in the array for the different value and add quantity++ in the infinity
enter image description here
what's the solution is for the good conditions in my code function?
Here I am using array to store date in local-storage. first add data that is stored after add another one the index value not increased. The newly add data only shows.
function save() {
var task = [];
localStorage.getItem('task');
task.push(document.getElementById("txt1").value);
console.log(task);
localStorage.setItem('array', task);
}
i have this object:
card: { customFields [ { id, value }, {id , value } ... ] }
A customFields array is inside cards, which contans elements consisting of an id and a value.
Now i want to update a certain element inside of the array, which can be done by doing something like this:
modifier.$set.customFields.0.value = x
but i have the number of the index only in a variable, so i tried:
const index = getTargetIndex();
modifier.$set.customFields[index].value = x
but it didn't work...
What do i have to add to the modifier.$set to update an element in this array?
Alternate Solution: i have the id of the element in the array if the update can be done on value by using the id.
Found a solution:
modifier.$set[`customFields.${ index }.value`]
It looks like you'll need to do it using a second update:
update(selector, modifier, options, callback) {
let i = 1;
let val = 20;
// The field in the array you want to modify
let _modifier = {$set: {"customFields.$.value": val}};
// The selector for main element and the array element
let _selector = Object.assign(selector, {"customFields.id": i});
// Update the array
super.update(_selector, _modifier);
// Continue with the actual update
return super.update(selector, modifier, options, callback);
}
I'm assuming it's safe to call super.update() twice in the same hook.
I would like to define the id for each item added through the code below.
The value I would like to define would differ with each record based on the value extracted from the csv.
I am unable to asign the value and the documentation seems to be lacking.
Code:
<script>
var myList;
function doOnLoad() {
myList = new dhtmlXList({
id:"#data2#",
container:"data_container",
template:"#data1#<br/>#data2#"
});
myList.load("../clients.csv","csv");
}
</script>
The below link does have information on changing the ID when adding an item, but not when loading them.
http://docs.dhtmlx.com/list__manipulating_data.html#addingitems
Any assistance would be great. Thank you :)
You can use changeId API
myList.load("../common/data.csv","csv", function(){
var count = this.dataCount();
for (var i = 0; i < count; i++) {
var item = this.item(this.idByIndex(i));
this.changeId(item.id, generate_new_id(item));
}
});
here, after data loading, code iterates other all items and change their IDs ( generate_new_id is your function, which returns new id, based on the item objec )
I am pretty new to the 'game' and was wondering if it's possible to order newly added data (through a form and inputs) to the Firebase numerically so each new data entry gets the ID (number of the last added data +1).
To make it more clear, underneath you can find a screenshot of how data is currently being added right now. The datapoint 0-7 are existing (JSON imported data) and the ones with the randomly created ID belong to new entries. I would like to have the entries to comply to the numbering inside of my Firebase, because otherwise my D3 bar chart won't be visualised.
var firebaseData = new Firebase("https://assignment5.firebaseio.com");
function funct1(evt)
{
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
firebaseData.push().set({games: gameName, medals: medalCount, summergames: bool});
evt.preventDefault();
}
var submit = document.getElementsByTagName('button')[0];
submit.onclick = funct1;
UPDATE:
function funct1(evt)
{
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
for (var i = 0; i < 10; i++)
{
firebaseData.child('7' + i).set({games: gameName, medals: medalCount, summergames: bool}(i)); };
Problem:
There are two ways to generate ids for your document nodes.
Calling .push() on your reference will generate that unique id.
Calling .set() on your reference will allow you to use your own
id.
Right now you're using .push().set({}), so push will generate an new id and the set will simply set the data.
// These two methods are equivalent
listRef.push().set({user_id: 'wilma', text: 'Hello'});
listRef.push({user_id: 'wilma', text: 'Hello'});
Using .set() without .push() will allow you to control your own id.
Using .push():
When managing lists of data in Firebase, it's important to use unique generated IDs since the data is updating in real time. If integer ids are being used data can be easily overwritten.
Just because you have an unique id, doesn't mean you can't query through your data by your ids. You can loop through a parent reference and get all of the child references as well.
var listRef = new Firebase('https://YOUR-FIREBASE.firebaseio.com/items');
// constructor for item
function Item(id) {
this.id = id;
};
// add the items to firebase
for (var i = 0; i < 10; i++) {
listRef.push(new Item(i));
};
// This will generate the following structure
// - items
// - LGAJlkejagae
// - id: 0
// now we can loop through all of the items
listRef.once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var name = childSnapshot.name();
var childData = childSnapshot.val();
console.log(name); // unique id
console.log(childData); // actual data
console.log(childData.id); // this is the id you're looking for
});
});
Within the childData variable you can access your data such as the id you want.
Using .set()
If you want to manage your own ids you can use set, but you need to change the child reference as you add items.
for (var i = 0; i < 10; i++) {
// Now this will create an item with the id number
// ex: https://YOUR-FIREBASE.firebaseio.com/items/1
listRef.child('/' + i).set(new Item(i));
};
// The above loop with create the following structure.
// - items
// - 0
// - id: 0
To get the data you can use the same method above to loop through all of the child items in the node.
So which one to use?
Use .push() when you don't want your data to be easily overwritten.
Use .set() when your id is really, really important to you and you don't care about your data being easily overwritten.
EDIT
The problem you're having is that you need to know the total amount of items in the list. This feature is not implemented in Firebase so you'll need to load the data and grab the number of items. I'd recommend doing this when the page loads and caching that count if you really desire to maintain that id structure. This will cause performance issues.
However, if you know what you need to index off of, or don't care to overwrite your index I wouldn't load the data from firebase.
In your case your code would look something like this:
// this variable will store all your data, try to not put it in global scope
var firebaseData = new Firebase('your-firebase-url/data');
var allData = null;
// if you don't need to load the data then just use this variable to increment
var allDataCount = 0;
// be wary since this is an async call, it may not be available for your
// function below. Look into using a deferred instead.
firebaseData.once('value', function(snapshot) {
allData = snapshot.val();
allDataCount = snapshot.numChildren(); // this is the index to increment off of
});
// assuming this is some click event that adds the data it should
function funct1(evt) {
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
firebaseData.child('/' + allDataCount).set({
games: gameName,
medals: medalCount,
summergames: bool
});
allDataCount += 1; // increment since we still don't have the reference
};
For more information about managing lists in Firebase, there's a good article in the Firebase API Docs. https://www.firebase.com/docs/managing-lists.html