Is there a way to let .push() || .push().key generate one key for chained .push()?
function saveItem(){
const itemId = ref.push().key;
let newItem = {id: itemId}
ref.child(`items`)
.push(newItem)
.then(() => ref.child(`users/${uid}/items`)
.push(itemId)
}
In example above I will generate 3 different keys instead of generating one even though there is itemId variable.
Every push() call will create a new id. Chained push that is called three times will create three unique ids. So you need to use it only once to get unique id. Then if you want to write to a certain place(in your case to the 'items/id') you can use set() or update(). Set will overwrite all data at given location. While update will update only needed field at a lower level keys. Example below:
function saveItem(){
let ref = firebase.database().ref();
const itemId = ref.child('items').push().key;
let newItem = {some: data}
ref.child(`items/${itemId}`)
.set(newItem)
.then(() => {
let updates = {};
updates[`/items/${itemId}/someField`] = newData;
ref.update(updates);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With