Home > Back-end >  firebase - add and remove new values into an array
firebase - add and remove new values into an array

Time:06-04

I have two array in firebase realtime database that will manage user followers and following. I've created this function in my vue app that will add the follow if an user click on the button in the profile of another user and the following into the profile of the user who clicked:

        async followUser() {
            await update(ref(db, 'Users/'  this.profileKey), {
                followers: [store.currentUser.uid]
            })
            await update(ref(db, 'Users/'  store.currentUserKey), {
                following: [this.$route.params.uid]
            })
        }

At the moment I've tested on two profile I've created ad-hoc and the function act as expected but I have a doubt about it. If the user will start follow other users, will the new entries will be added correctly into the existing array or all the data will be overwritten? What's the correct way to push or remove valuse into an array stored in firebase realtime database?

CodePudding user response:

There is no atomic way to add an item to or remove an item from an array in the Firebase Realtime Database API. You'll have to read the entire array, add the item, and write the array back.

Better would be to store the followers and followings as maps instead of arrays, with values of true (since you can't have a key without a value in Firebase. If you'd do that, adding a new user follower would be:

set(ref(db, 'Users/'  this.profileKey '/followers/' store.currentUser.uid), true)

And removing a follow would be:

set(ref(db, 'Users/'  this.profileKey '/followers/' store.currentUser.uid), null)

Or

remote(ref(db, 'Users/'  this.profileKey '/followers/' store.currentUser.uid))

Also see: Best Practices: Arrays in Firebase.

  • Related