As I am new to the firebase and React, I appreciate your help as I have tried everything almost.
Following is my data structure in firebase.
When I add new Beverage type i.e. Milk with its fields i.e. with nested nodes and data to Products, firebase generate child node based on random number. Please help me and let me know how I can create custom child nodes with no text as mentioned in the data structure. in actual I have ready json as mentioned below and want to add new beverage type with its details as mentioned below in json.
"Id" : 1,
"Milk" : {
"Id" : 2,
"Imported Milks" : {
"Frosted Milk" : 20,
"Milk Up" : 10
},
"Local Milks" : {
"Cow Power" : 5,
"Milk Man" : 3
}
}
following is my code:
let product = "Milk";
const dbUpdate = await firebase.database().ref("Products");
//this.state.selectedCategory is Milk
await dbUpdate.child(this.state.selectedCategory).set(
{
product:
{
Id: item.Id,
"Imported Milks": {
"Frosted Milk": 20,
"Milk Up" : 10
}
}
}
);
I just made some changes to my code. It worked but set is deleted all previous records and added only new one.
let product = "Milk";
const dbUpdate = await firebase.database().ref("Products");
//this.state.selectedCategory is Milk
await dbUpdate.set(
{
this.state.selectedCategory:{
product:
{
Id: item.Id,
"Imported Milks": {
"Frosted Milk": 20,
"Milk Up" : 10
}
}
}
}
);
Thanks
If you want to add a new beverage with a key you specify yourself, you can do:
firebase.database().ref("Products/Beverages/Beers").child("Lagunitas").set(1);
So the important thing here is that we don't call push (which would generate a ID), but instead specify your own key (in the call to child() in this case).
If you want to set an entire JSON object, that'd be:
firebase.database().ref("Products").set({
Beverages: {
Beers: {
Id: 1,
"Imported Beers": {
Bella: 20,
LoveBug: 5
}
}
}
})
If you want to use the value of your product variable in the path to update a path in the database, you can do:
let product = "Milk";
const dbUpdate = await firebase.database().ref("Products");
// 👇
await dbUpdate.child(this.state.selectedCategory).update({
[product]: // 👈 Use [] to use the value of the variable
{
Id: item.Id,
"Imported Milks": {
"Frosted Milk": 20,
"Milk Up" : 10
}
}
});
This will set the Milk key in selectedCategory, but leave other child keys unmodified.
If you want to perform a deep update of one key in a branch, you can also use a path as the key. So for example to add the two items to Imported Milks, but leave any other values unmodified, you'd do:
firebase.database().ref("Products").update({
"Beverages/Milk/Imported Milks/Frosted Milk": 20,
"Beverages/Milk/Imported Milks/Milk Up" : 10
})