In my Firebase Realtime Database I have a structure like this:
Now I want to implement a function that adds habits to this collection. Right now I am using the following code (with input.value being the value of an input element). However, the Firebase push method creates a random key everytime it adds a new element. I would like the keys to be numbers / index values, just like the elements in the screenshot have the keys 0 and 1. Is there a Firebase method that works like this (if so, I couldn't find it), and if not, how would I best implement this, so that the next element would be added with the key 2 and so on?
function addHabit() {
push(reference(database, "habits"), {
text: input.value,
interval: "Daily",
});
}
Using sequential numeric keys with Firebase is an anti-pattern as determining the next index requires you to read the existing length (so won't work while offline) and that all users agree on that length (so won't work in multi-user scenarios). To store lists of data, it's better to use Firebase's push() operator.
For more on this, see Best Practices: Arrays in Firebase.