1

I am succesfully updating my user's profile picture on their profile and on all of their reviews posted with this function:

export const storeUserProfileImage = (url) => {
    const { currentUser } = firebase.auth();

        firebase.database().ref(`/users/${currentUser.uid}/profilePic`)
        .update({ url });

        firebase.database().ref('reviews')
          .orderByChild('username')
          .equalTo('User3')
          .once('value', (snapshot) => {
            snapshot.forEach((child) => {
              child.ref.update({ profilePic: url });
            });
        });
  };

I am aware that I should be using an atomic update to do this so the data updates at the same time (in case a user leaves the app or something else goes wrong). I am confused on how I can accomplish this when querying over child values.

Any help or guidance would be greatly appreciated!

hugger
  • 426
  • 4
  • 19

1 Answers1

1

Declare a variable to store all the updates. Add the updates as you read them on your listener's loop. When the loop is finished, run the atomic update.

export const storeUserProfileImage = (url) => {
    const { currentUser } = firebase.auth();

        firebase.database().ref('reviews')
          .orderByChild('username')
          .equalTo('User3')
          .once('value', (snapshot) => {

            var updates = {};
            updates[`/users/${currentUser.uid}/profilePic`] = url;

            snapshot.forEach((child) => {
              updates[`/reviews/${child.key}/profilePic`] = url;
            });

            firebase.database().ref().update(updates);

        });
};
  • Consider [accepting this answer](https://meta.stackexchange.com/a/5235/364194) if it answers your question so that others know it has been solved. – Rosário Pereira Fernandes Jul 27 '18 at 20:51
  • I just accepted it - thanks for the lesson haha... I wasn’t aware of how to do that. – hugger Jul 27 '18 at 21:18
  • Hey Rosario - what if it was a case where I had to loop through multiple references? In my case being Reviews (like we already resolved) and contributions with the exact same JSON structure. – hugger Jul 28 '18 at 19:07