0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.