Vuex and Firebase storage errors
I have the following setup in my vuex store: My users are logged in with Firebase authentication. When logged in firebase.auth().onAuthStateChanged
, a user
- is called , state.user
but also stored in the Firebase database. The moment I add the last part of my code ( database.ref...
), my console explodes with errors. The errors, however, are not related to Firebase, but to Vuex.
The errors are as follows (x80):
[Vue warn]: Error in callback for watcher function "() {return this._data. $$ state}":
Error: [vuex] Do not mutate vuex store state outside of mutation handlers.
My code still works, but during development I don't want to see 80 errors when a user logs in. How can I get rid of these errors?
// actions
const actions = {
startListeningToAuth ({ commit }) {
firebase.auth().onAuthStateChanged((user) => {
commit(types.SET_USER, { user })
})
}
}
// mutations
const mutations = {
[types.SET_USER] (state, { user }) {
state.user = user
if (user) {
database.ref('users/' + user.uid).set({
name: user.displayName,
email: user.email,
photo_url: user.photoURL
})
}
}
}
source to share
You can use toJSON () method for firebase.User interface
commit(types.SET_USER, { user.toJSON() })
This will allow user data to be added to your store without any warnings, but my guess is you might lose realtime user state from firebase.
See https://firebase.google.com/docs/reference/js/firebase.User#toJSON
source to share
Mutations should only contain code that directly affects vuex state
.
You are getting errors because database.ref()
most likely modifying the object user
in some way. In your mutation state.user = user
makes it so that your object state.user
refers to the same object as your variable user
. So, if it user
changes outside of the mutation, the state will change as well and Vue will yell at you.
You have to move your call database.ref()
to the appropriate action method and then commit the mutation. Since it database.ref()
is asynchronous, you need to wait for this method to complete before committing the mutation:
// actions
const actions = {
startListeningToAuth ({ commit }) {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
database.ref('users/' + user.uid).set({
name: user.displayName,
email: user.email,
photo_url: user.photoURL
}).then(() => {
commit(types.SET_USER, { user })
})
}
})
}
}
// mutations
const mutations = {
[types.SET_USER] (state, { user }) {
state.user = user
}
}
source to share
Do you want to set user data after registration? this is my code to do it
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((user) => {
//init user
userRef.child(user.uid).set({
email: email,
//Other data
});
})
.catch((error) => {
state.isRegenter code hereister = false;
console.log(error);
});
source to share