Leo Leo - 7 months ago 94
Swift Question

When I try to save data to Firebase it only updates the existing data, Swift, Firebase

The way I set up my database structure was like this:

It starts with Lists then there is a child that shows the users UID then inside that there is one item.


The one item inside the UID gets updated every time I attempt to save new data. Instead of adding another item the same one just keeps changing. I was wondering how I could instead of update the same one item every time add more items.

The way that I save my data is with this line of code.

let user = FIRAuth.auth()?.currentUser
let item: String = self.ItemTextField.text!
self.ref.child("Lists").child(user!.uid).setValue(["Items": item])


More idiomatic is to store the list of items with so-called push ids:

    -Km....: "Yoghurt"

You'd do this with:


The childByAutoId() generates a unique, sequential ID. It's similar to an array index, but this one works reliably in multi-user environments and when users can be offline. Read this blog post about these so-called push ids.

Alternatively you can use the name of the item as the key (if the item has to be unique in the list):

    "Yoghurt": true

In that case the code becomes:


One thing you'll note is that both of these approaches only deal with the newly added item, instead of the list of items as a whole. This is a general pattern you'll see when using Firebase. By isolating your modifications, your app will be more scalable without users getting into each other's way.