Vuex module + Firebase auth
Most of the time, it might be best not to use vuew with firebase. But some times you need to, or you just want to use the authentication part. Here is a way to implement firebase authentication via a Vuex module:
import firebase from 'firebase/app';
import 'firebase/database';
import 'firebase/auth';
const FBConfig = {
// your firebase credentials...
};
firebase.initializeApp(FBConfig);
const firebaseModule = {
state: {
user: null,
error: '',
initialized: false,
},
mutations: {
SET_USER(state, user) {
state.user = user;
},
},
actions: {
init({ commit, state }) {
if (state.initialized) {
return;
}
state.initialized = true;
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log(user);
commit('SET_USER', user);
} else {
commit('SET_USER', null);
}
});
},
login({ state, dispatch }, credentials) {
return dispatch('init')
.then(() => firebase.auth().signInWithEmailAndPassword(credentials.email, credentials.password))
.then((res) => {
console.log(res);
})
.catch(function (error) {
console.log(error);
state.error = error;
});
},
signup({ state, dispatch }, credentials) {
return dispatch('init')
.then(() => firebase.auth().createUserWithEmailAndPassword(credentials.email, credentials.password))
.then((res) => {
console.log(res);
})
.catch(function (error) {
console.log(error);
state.error = error;
});
},
},
};
export default firebaseModule;