jgravois
jgravois

Reputation: 2579

Firestore data not changed in Vuex

I have this Vuex action that should change a users status on logout but since false values aren't save in Firestore, it isn't working

logoutUser({commit, state}) {
        let user = firebase.auth().currentUser;

        db
            .collection('users')
            .where('user_id', '==', user.uid)
            .get()
            .then(snapshot => {
                snapshot.forEach((doc) => {
                    db
                        .collection('users')
                        .doc(doc.id)
                        .update({
                            is_online: false
                        });
                    localStorage.setItem('firebase_user', null);
                    firebase
                        .auth()
                        .signOut()
                        .then(() => {
                            commit('SET_AUTHENTICATED', false);
                            commit('SET_CURRENT_USER', null);
                        });
                });
            });
    }

I am just starting with Firestore so I would appreciate any assistance or recommendations ... Thanks!!!

Upvotes: 0

Views: 87

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83103

The following should work (not tested). You need to chain the promises returned by the asynchronous methods (update() and signOut()).

I make the assumption that there is only one user with user.uid in the users collection, therefore I use snapshot.docs[0] to get the unique user document, instead of using forEach()

logoutUser({ commit, state }) {
  const user = firebase.auth().currentUser;
  db.collection('users')
    .where('user_id', '==', user.uid)
    .get()
    .then(snapshot => {
      const userDocSnapshot = snapshot.docs[0];

      return userDocSnapshot.ref.update({
        is_online: false
      });
    })
    .then(() => {
      return firebase.auth().signOut();
    })
    .then(() => {
      localStorage.setItem('firebase_user', null);
      commit('SET_AUTHENTICATED', false);
      commit('SET_CURRENT_USER', null);
    });
}

Upvotes: 1

Related Questions