Wednesday 26 January 2022

Vue.js - How to use Set VUEX values in main.js

 The answer to 'How to use Set VUEX values in main.js' is that you don't ! 


Another niche note from myself for a Google search term that I made that this blog would have save me a bit of time chasing around the houses. 


I highly recommend the YouTube video for solving this and other Vuex issues - https://www.youtube.com/watch?v=oxUyIzDbZts&t=629s


The issue I had to solve was that I'd written some code where I was using 'localStorage' when the value should be stored in VUEX .  This was being done in the main.js page. 



firebase.auth().onAuthStateChanged(async function (user) {
console.log('Auth State Checked')
if (user) {
user.getIdTokenResult().then(idTokenResult => {
if (idTokenResult.claims.admin === true) {
localStorage.adminClaim = true
}
});
}
})


The main thing here is, we can't use Vuex from the main.js page and you can't 'commit' to Vuex from here.  That will done in a VUEX 'action'.  

In store/index.js

export default new Vuex.Store({
state: {
adminRole: false,
},
mutations: {
//syncrous
setAdminRole(state, payload) {
state.adminRole = payload;
}
},
actions: {
//asyncronous
async setAdminRole(state) {
firebase.auth().onAuthStateChanged(async function (user) {
console.log('Auth State Checked')
if (user) {
user.getIdTokenResult().then(idTokenResult => {
console.log('IdTokenResult for user', idTokenResult);
console.log('idTokenResult.claims.admin',idTokenResult.claims.admin);
if (idTokenResult.claims.admin === true) {
state.commit("setAdminRole", true);
}
});
}
})
}
},
modules: {},
getters: {
getAdminRole: state => state.adminRole,
},
});


And then in App.vue we can Dispatch our 'action' like this. 

export default {
mounted(){
this.$store.dispatch("setAdminRole");
}
};


Next up is to call it in the page you want to access that data.  In our case the TopHeader page. 


Note in the video above at 8.40, he talks about timing issues.  Which is why mounted doesn’t work and we need to use computed. 



export default {
data() {
return {
},
name: "top-header",
mounted() {
},
computed: {
adminRole(){
return this.$store.getters.getAdminRole;
},
}
};


This will load a data variable 'adminRole' with our Boolean task.  So using 

{{ adminRole }}

in the template, would output either True or False. 







No comments: