VueJS Axios pass Id token to a global header - vue.js

I took the back-end response token and store it in store.js as a state.
How do I pass that token value to the main.js? I do want to attach it to the Authorization header. This is my code.
store.js
state:{
idToken:"a sample id token"
}
main.js
axios.defaults.headers.common['Authorization']=
How do I pass that token value to the Authorization header.
Thank you.

#Shubham Patel You should watch changes of the returnToken. Then, do hearder reset in the watcher. The token refreshing should also be made with mutations.
Maybe something like:
Main.js:
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'returnToken'
])
},
watch: {
returnToken(newToken) {
this.$axios.defaults.headers.common['Authorization'] = newToken
}
}
}
Store.js:
export default new Vuex.Store({
state: {
idToken:"a sample id token"
},
getters: {
returnToken: state => {
return state.idToken
}
},
mutations: {
updateToken(state, {token}) {
state.idToken = token
}
}
})
Then somewhare else:
let token = await loadToken()
store.commit('updateToken', {token})

You can write a getter in Vuex which will return your current authentication token.
const store = new Vuex.Store({
state: {
idToken:"a sample id token"
},
getters: {
returnToken: state => {
return state.idToken
}
}
})
Then import the getter using
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'returnToken'
])
}
}
Then write
axios.defaults.headers.common['Authorization']=this.returnToken()
Reference

Related

Axios - get data from api in vuex actions?

How to correctly transfer or rewrite the function in actions that will receive the first photo from each album in?
my photos models:
import { api } from "#/apis/config";
const endPoint = 'photos'
const state = {
photos: []
}
const getters = {}
const mutations = {
SET_PHOTOS(state, data) {
state.photos = data
}
}
const actions = {
loadMore(id) {
api.get(`photos?albumId=${id}`).then(response => {
return response.data[0].thumbnailUrl;
});
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
};
And my album component:
...
<script>
import {mapActions} from "vuex";
export default {
name: "GridAlbums",
props: ['album'],
data() {
return {
loading: true,
errored: false,
photo: null
}
},
mounted() {
this.photo = this.loadMore(this.album.id)
},
methods: {
...mapActions("photos", ["loadMore"])
}
}
</script>
...
Here is my configuration file for api, where VUE_APP_HOST is https://jsonplaceholder.typicode.com/
import axios from 'axios'
export const api = axios.create({
baseURL: process.env.VUE_APP_HOST,
})
api.interceptors.response.use(
response => {
return response
},
error => {
return Promise.reject(error)
}
)
If you get the data this way, then everything turns out as it should:
Try adding async / await in vuex actions, because actions must be asynchronous and store and mutations synchronous.
Also use try / catch instead Promise that way you keep your code cleaner

How to get value of Vuex getter inside of Vue local data object

Hey this seemed to be pretty simple, but I just can't figure out how to get my loggedInUser object to work outside the template. I read through a bunch of other answers and I know I have to do something to store the getter in a local data object.
I have a temporary 'id' object set up because that's what I ultimately want to set to loggedInUser.id in order to attach to my Axios request.
Here's the page I want to make changes on:
<script>
import { mapGetters } from 'vuex'
// import vuex from 'vuex'
export default {
data: () => ({
results: "",
id: "15",
}),
computed: {
...mapGetters(['loggedInUser'])
},
// var id = {{loggedInUser}};
methods: {
getData() {
this.$axios.get('http://127.0.0.1:8000/api/v1/actors/',
{params: {user: this.id} }
)
.then(response => {this.results = response.data});
}
}
}
</script>
and here's my index.js for store:
export const getters = {
isAuthenticated(state) {
return state.auth.loggedIn
},
loggedInUser(state) {
return state.auth.user
}
}
The mapGetters helper simply maps store getters to local computed
properties
This:
computed: {
...mapGetters(['loggedInUser'])
},
Is equivalent to this:
computed: {
loggedInUser() {
return this.$store.getters.loggedInUser
},
},
Replace this.id with this.loggedInUser.id in your axios request, and get rid of the temporary id data property.
getData() {
this.$axios.get('http://127.0.0.1:8000/api/v1/actors/', {
params: {
user: this.loggedInUser.id
}
})
.then(response => {
this.results = response.data
});
}
We are assuming getData only gets called when the user is authenticated. If that's not the case, have in mind this.loggedInUser may be null or undefined and accessing this.loggedInUser.id will throw an error.

Setting value to input field using Vuex store modules

I have a vuex in module mode that fetching the data of a user:
store/modules/users.js
import axios from "axios";
export const state = () => ({
user: {}
});
// Sets the values of data in states
export const mutations = {
SET_USER(state, user) {
state.user = user;
}
};
export const actions = {
fetchUser({ commit }, id) {
console.log(`Fetching User with ID: ${id}`);
return axios.get(`${process.env.BASE_URL}/users/${id}`)
.then(response => {
commit("SET_USER", response.data.data.result);
})
.catch(err => {
console.log(err);
});
}
};
// retrieves the data from the state
export const getters = {
getUser(state) {
return state.user;
}
};
then on my template pages/users/_id/index.vue
<b-form-input v-model="name" type="text"></b-form-input>
export default {
data() {
return {
name: ""
}
},
created() {
// fetch user from API
this.$store.dispatch("fetchUser", this.$route.params.id);
}
}
Now I check the getters I have object getUser and I can see the attribute. How can I assign the name value from vuex getters to the input field?
watcher is probably what you need
export default {
// ...
watch: {
'$store.getters.getUser'(user) {
this.name = user.name;
},
},
}
While Jacob's answer isn't necessarily incorrect, it's better practice to use a computed property instead. You can read about that here
computed: {
user(){
return this.$store.getters.getUser
}
}
Then access name via {{user.name}} or create a name computed property
computed: {
name(){
return this.$store.getters.getUser.name
}
}
Edit: fiddle as example https://jsfiddle.net/uy47cdnw/
Edit2: Please not that if you want to mutate object via that input field, you should use the link Jacob provided.

VueJS - Vuex Assign data in a mutation

I'm getting used to Vuex as I need to be able to have a store that I can easily access and update when another component is changed.
Currently, my store looks like the following:
import vue from 'vue';
import Vuex from 'vuex';
vue.use(Vuex);
export default new Vuex.Store({
state: {
users: {
columns: [],
model: [],
}
},
mutations: {
fetchUsers: function(state) {
axios.get(`/users?search_input=`)
.then(function(response) {
});
}
}
});
The columns and model is dynamically pulled down from an ajax request and my Users looks like the following:
<script>
export default {
mounted() {
this.$store.commit('fetchUsers');
},
computed: {
columns() {
return this.$store.state.users.columns;
}
model() {
return this.$store.state.users.model
}
},
}
</script>
My problem is that the application needs to have data preloaded from Ajax. For example columns are set from an ajax request in fetchUsers and inside the Users I use this.$store.commit('fetchUsers'); but is there an alternative way I can do that without using commit preferably inside the store itself?
In the store u can load ur data asynchronously via actions then commit the changes using a mutation.
import vue from 'vue';
import Vuex from 'vuex';
vue.use(Vuex);
export default new Vuex.Store({
state: {
users: {
columns: [],
model: [],
}
},
actions: {
fetchUsers: function( context ) {
axios.get(`/users?search_input=`)
.then( function( response ) {
context.commit( "FETCHUSERS", {
columns: response.columns,
model: response.model
});
});
}
}
mutations: {
FETCHUSERS: function( state, payload ) {
state.users.columns = payload.columns;
state.users.model = payload.model;
}
}
});
Dispatch the action from the component
<script>
export default {
.....
methods: {
fetchUsers: function() {
this.$store.dispatch( "fetchUsers" );
}
}
}
</script>
Mutations must be synchronous: https://vuex.vuejs.org/en/mutations.html
You should move ajax request into actions, which can be async. You get data in the action, commit mutation giving received data as a payload, and mutation assigns a value to the state property.
Alternatively, you can make async request in component method, and assign a value to the store property directly: this.$store.state.prop = value

Making Async Calls With Vuex

I'm just starting to learn Vuex here. Until now I've been storing shared data in a store.js file and importing store in every module but this is getting annoying and I'm worried about mutating state.
What I'm struggling with is how to import data from firebase using Vuex. From what I understand only actions can make async calls but only mutations can update the state?
Right now I'm making calls to firebase from my mutations object and it seems to be working fine. Honestly, all the context, commit, dispatch, etc. seems a bit overload. I'd like to just be able to use the minimal amount of Vuex necessary to be productive.
In the docs it looks like I can write some code that updates the state in the mutations object like below, import it into my component in the computed property and then just trigger a state update using store.commit('increment'). This seems like the minimum amount necessary to use Vuex but then where do actions come in? Confused :( Any help on the best way to do this or best practices would be appreciated!
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
My code is below
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const db = firebase.database();
const auth = firebase.auth();
const store = new Vuex.Store({
state: {
userInfo: {},
users: {},
resources: [],
postKey: ''
},
mutations: {
// Get data from a firebase path & put in state object
getResources: function (state) {
var resourcesRef = db.ref('resources');
resourcesRef.on('value', snapshot => {
state.resources.push(snapshot.val());
})
},
getUsers: function (state) {
var usersRef = db.ref('users');
usersRef.on('value', snapshot => {
state.users = snapshot.val();
})
},
toggleSignIn: function (state) {
if (!auth.currentUser) {
console.log("Signing in...");
var provider = new firebase.auth.GoogleAuthProvider();
auth.signInWithPopup(provider).then( result => {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// Set a user
var uid = user.uid;
db.ref('users/' + user.uid).set({
name: user.displayName,
email: user.email,
profilePicture : user.photoURL,
});
state.userInfo = user;
// ...
}).catch( error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
} else {
console.log('Signing out...');
auth.signOut();
}
}
}
})
export default store
main.js
import Vue from 'vue'
import App from './App'
import store from './store'
new Vue({
el: '#app',
store, // Inject store into all child components
template: '<App/>',
components: { App }
})
App.vue
<template>
<div id="app">
<button v-on:click="toggleSignIn">Click me</button>
</div>
</template>
<script>
import Hello from './components/Hello'
export default {
name: 'app',
components: {
Hello
},
created: function () {
this.$store.commit('getResources'); // Trigger state change
this.$store.commit('getUsers'); // Trigger state change
},
computed: {
state () {
return this.$store.state // Get Vuex state into my component
}
},
methods: {
toggleSignIn () {
this.$store.commit('toggleSignIn'); // Trigger state change
}
}
}
</script>
<style>
</style>
All AJAX should be going into actions instead of mutations. So the process would start by calling your action
...which commits data from the ajax callback to a mutation
...which is responsible for updating the vuex state.
Reference: http://vuex.vuejs.org/en/actions.html
Here is an example:
// vuex store
state: {
savedData: null
},
mutations: {
updateSavedData (state, data) {
state.savedData = data
}
},
actions: {
fetchData ({ commit }) {
this.$http({
url: 'some-endpoint',
method: 'GET'
}).then(function (response) {
commit('updateSavedData', response.data)
}, function () {
console.log('error')
})
}
}
Then to call your ajax, you will have to call the action now by doing this:
store.dispatch('fetchData')
In your case, just replace this.$http({...}).then(...) with your firebase ajax and call your action in the callback.