Hello, I am new to using Vue.js and I am currently integrating Firebase for authentication in my project. Below is the Firebase code that I have separated into a different JavaScript file. This file contains all the mutations, states, actions, and getters which are then imported into various components.
import firebase from "firebase/app";
import "firebase/auth";
export default {
state: {
loggedInUser:
localStorage.getItem("userInfo") != null
? JSON.parse(localStorage.getItem("userInfo"))
: null,
loading: false,
error: null
},
getters: {
loggedInUser: (state) => state.loggedInUser,
loading: (state) => state.loading,
error: (state) => state.error
},
mutations: {
setUser(state, data) {
state.loggedInUser = data;
state.loading = false;
state.error = null;
},
setLogout(state) {
state.loggedInUser = null;
state.loading = false;
state.error = null;
},
setLoading(state, data) {
state.loading = data;
state.error = null;
},
setError(state, data) {
state.error = data;
state.loggedInUser = null;
state.loading = false;
},
clearError(state) {
state.error = null;
}
},
actions: {
login({ commit }, data) {
commit("clearError");
commit("setLoading", true);
firebase
.auth()
.signInWithEmailAndPassword(data.email, data.password)
.then((user) => {
const newUser = { uid: user.user.uid };
localStorage.setItem("userInfo", JSON.stringify(newUser));
commit("setUser", { uid: user.user.uid });
console.log("userInfo");
})
.catch(function (error) {
localStorage.removeItem("userInfo");
commit("setError", error);
});
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
let email = user.email;
} else {
// User is signed out.
}
});
},
signUserUp({ commit }, data) {
commit("setLoading", true);
commit("clearError");
firebase
.auth()
.createUserWithEmailAndPassword(data.email, data.password)
.then((user) => {
commit("setLoading", false);
const newUser = {
uid: user.user.uid
};
console.log(newUser);
localStorage.setItem("userInfo", JSON.stringify(newUser));
commit("setUser", newUser);
})
.catch((error) => {
commit("setLoading", false);
commit("setError", error);
localStorage.removeItem("userInfo");
console.log(error);
});
},
signOut({ commit }) {
firebase
.auth()
.signOut()
.then(
() => {
localStorage.removeItem("userInfo");
commit("setLogout");
},
(_error) => {}
);
}
}
};
I am importing it into the component like this:
import { mapGetters, mapActions, mapState } from "vuex";
export default {
components: {},
data() {
return {
email: ""
};
},
computed: {
...mapGetters(["getSideBarToggleProperties"]),
...mapState(["loggedInUser"])
},
methods: {
...mapActions(["signOut", "login"]),
getLogin() {
this.login({ email: this.email });
},
Then I call the method 'getLogin' using @click to display like this:
<a class="dropdown-item" id="testing">{{loggedInUser}}</a>