Uncaught (in promise) TypeError: Cannot create property 'token' on string - vue.js

Am trying to implement authentication using vuex. I have a register component and also a auth.js for submiting data.
My backend API are working fine but the issue is when i try to login. When i console log in action method am able to get the token.
when i console log before the SET_TOKEN mutation am also able to get data.
But in mutations the data is received like an object. How do I solve the error?
import axios from "axios"
export default{
namespaced: true,
state: {
token: null,
user: null
},
mutations: {
SET_TOKEN(access_token, state){
console.log(this, access_token)
state.token = this,access_token
},
},
actions: {
async loginUser({ dispatch }, form) {
let response = await axios.post('/api/auth/login', form)
dispatch('attempt', response.data.data.access_token)
},
async attempt({ commit }, access_token){
commit('SET_TOKEN', access_token)
}
}
}

I think you mixed up the order of mutation parameters a little bit. First is state, second is payload (token in your case)
SET_TOKEN(state, token) {
state.token = token;
},

Related

Vuex state property does not update

I'm developing a simple social media at the moment. I have a problem. token state property doesn't update at all, even when there is a token item in the localStorage. Here is my unfinished project on Github. And here is the store where the token property is stored (path: resources/js/store/modules/middleware.js):
const state = {
user: {
loggedIn: false,
isSubscribed: false,
token: localStorage.getItem('token') || ''
},
}
const actions = {}
const mutations = {}
const getters = {
auth(state) {
return state.user
}
}
export default {
namespaced: false,
state,
actions,
mutations,
getters
}
At first I thought that the state just updates before token item appears. So I decided to print the token in the console after 10 seconds (path of the file below: resources/js/middleware/auth.js):
export default function ({ next, store }) {
if (!store.getters.auth.token) {
console.log(store.getters.auth.token);
setTimeout(() => {
console.log(store.getters.auth.token);
}, 10000)
return next('login')
}
return next()
}
But the token was still an empty string. Here is how the console looks:
If you need something else to understand my question, feel free to ask!

how to get local storage token in vue methods property

i've a vue app which requires a token when sending a request each time i try to send a request i keep getting token not defined... here's the error
this how i call my methods property in script tag
<script>
import { mapActions } from "vuex";
import axios from "axios";
export default {
name: "Products",
data() {
return {
addresses: [],
products: []
};
},
methods: {
onDeleteAddress(id, index) {
axios
.delete(`http://localhost:5000/api/addresses/${this.$route.params.id}`,
{
headers: {
Authorization: "Bearer" + token,
"x-access-token": token
}
}
)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
}
};
</script>
this my vue template
Delete
this works in my mounted life cycle hook but when i input it in my methods component i get an error
const token = localStorage.getItem("token");
please how can i get the token stored in my local storage and define it in my vue methods conponent
In first make sure the item is already stored in the localstorage
Second instead of calling it from the localstorage it is better to define it in main.js file as global variable so you can use it free every where
Example
Vue.prototype.$globalData = Vue.observable({ token: localStorage.getItem("token") });
And now you can use it in your methods like this
this.$globalData.token
You can as much as you want variable in the globalData object

Passing OAuth token from one Vuejs component to another

I get OAuth token after successful OAuth login in a SuccessOAuth.vue component. I get the token details as follows:
checkforTokens(){
const queryString = this.$route.query;
console.log(queryString);
const token = this.$route.query.accessToken
console.log(token);
const secret = this.$route.query.tokenSecret
console.log(secret);
this.tokens.token = token;
this.tokens.secret = secret;
}
},
beforeMount() {
this.checkforTokens();
}
Now I want to use this token in another component apiCalls.vue where I use this token details to use call the API methods.
<script>
...
methods:{
getProductDetails() {
console.log("==========================================");
console.log(".. Get Product details....");
axios
.get("/auth/getShpDetails", {
params: {
token: this.tokens.token
}
})
.then(response => {
const productInfo = response.data;
console.log("Product info :" + productInfo);
});
},
}
</script>
How do I pass the token details from SuccessOAuth component to apiCalls. I tried using props method but I wasn't able to get the token value to the script tag, not sure about other methods used to pass i.e using $emit and using vuex. Please suggest the best way and the right solution for the problem.
As suggested by #Nishant Sham, I am just modifying the action method in index.js as seen below:
import Vue from 'vue'
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
token: ''
},
getters: {
getToken(state){
return state.token;
}
},
mutations: {
setToken(state, tokenValue){
state.token = tokenValue;
}
},
actions: {
setToken({commit}, tokenValue){
commit("setToken", tokenValue);
}
}
});
In your vue component you call getters and setters as follows:
<script>
//Set token value
var token = "dwe123313e12";//random token value assigned
this.$store.commit("setToken", token);
.....
//Get token value
var getToken = this.$store.getters.getToken;
</script>
You can keep your token inside Localstorage or cookies. And use as per your need. Here is the sample code for this:
const token = 'token'
export function getToken() {
return localStorage.getItem(token)
}
export function setToken(tokenData) {
return localStorage.setItem(token, tokenData)
}
export function removeToken() {
return localStorage.removeItem(token)
}
you can use Vuex for state management. Here is an article
One way to do this could be vuex
in the root, store create a token field and make one getter that you can call from any vue component and on any life cycle hook..
The second way can be that you set the token to localStorage and get/use it wherever you need it
I would prefer the vuex method that way it ensures a single source of truth...
Here is how to use vuex store
First of all install vuex depending on the vue version you are using, Generally, for the vue3 it is advisable to use npm i vuex#next
Create a Store folder inside your src folder and in there add the index.js with the following code
import { createStore } from "vuex";
import axios from "axios"; // I Use axios for making API CALLS hence this pkg
const store = createStore({
state() {
return {
token: null,
};
},
});
export default store;
This is the basic store and state of you app for now.
Lets start adding Actions first because actions are the async code used for making the API call and get the data from server
actions: {
async login(context, payload) {
try {
const result = await axios({
method: "POST",
url: "auth/login",
data: {
email: payload.email,
password: payload.password,
},
});
//If the Request Successed with Status 200
if (result.status === 200) {
//A: Extract the Token
const token = result.data.token;
//B. Token to LocalStorage Optional if you wish to set it to localstorgae
localStorage.setItem("token", token);
//c: UPDATE THE STATE by calling mutation
context.commit("setToken", {
token,
});
}
} catch (err) {
console.log(err);
}
},
},
Next step as you might have guessed adding mutation, which is used for updating your app state..
mutations: {
setToken(state, token) {
state.token = token;
},
},
Last the getter which you shall use to fetch the data either as computed inside your app components this is the
getters: {
getToken(state) {
return state.token;
},
},
Finally after all of this you index.js should look something like this
import { createStore } from "vuex";
import axios from "axios";
const store = createStore({
state() {
return {
token: null,
};
},
actions: {
async login(context, payload) {
try {
const result = await axios({
method: "POST",
url: "auth/login",
data: {
email: payload.email,
password: payload.password,
},
});
//If the Request Successed with Status 200
if (result.status === 200) {
//A: Extract the Token
const token = result.data.token;
//B. Token to LocalStorage Optional if you wish to set it to localstorgae
localStorage.setItem("token", token);
//c: UPDATE THE STATE by calling mutation
context.commit("setToken", {
token,
});
}
} catch (err) {
console.log(err);
}
},
},
mutations: {
setToken(state, token) {
state.token = token;
},
},
getters: {
getToken(state) {
return state.token;
},
},
});
export default store;
NOTE - This is a General representation of how the code for vuex should looks like there are a ton of other way to achive the same result, depending on you project requirment
The above code is not a final code, as it will need to be adjusted as per your test/example/project requirement

Keep Vuex state data without vuex-persist

weird question but i don't find an answer anywhere..
I return user data from an API call to Vuex. I save my user object into the Vuex state, along with a Token. (User object and Token are created and send back from Server to Vuex at the same time.)
Everything runs perfect and on the initialization of the component i fetch with a getter the user name etc.
But when i refresh i loose the user object from the state. But, i do not loose the Token. Which is weird cause i create them and return them together.
The question is, how can i keep the user in the state until i logout?
I don't need to keep them in localStorage or inside a cookie cause they are sensitive data (user). I just want to get them through a getter from my store. Which is the correct way to do it.
So vuex-persist is not an option..
Below you see my code:
store.js:
state: {
status: '',
token: localStorage.getItem('token'),
user: {}
},
mutations: {
auth_success(state, { token, user }) {
state.status = 'success';
state.token = token;
state.user = user;
},
actions: {
login({ commit }, user) {
return new Promise((resolve, reject) => {
commit('auth_request');
axios({
url: 'http://localhost:8085/login',
data: user,
method: 'POST'
.then((resp) => {
const token = resp.data.token;
const user = resp.data.user;
axios.defaults.headers.common['Authorization'] = token;
commit('auth_success', { token, user });
})
.catch((err) => {
commit('auth_error');
localStorage.removeItem('token');
reject(err);
});
}
},
getters: {
isLoggedIn(state) {
return state.token;
},
getUser(state){
return state.user;
}
User.vue:
<template>
<v-container>
<v-layout row wrap>
Welcome {{this.user.fullName}}
</v-layout>
</v-container>
</template>
<script>
export default {
data: function() {
return {
user: {}
}
},
mounted() {
this.getUser();
},
methods: {
getUser() {
return (this.user = this.$store.getters.getUser);
}
}
}
</script>
So to sum up:
Token stays in Vuex, user data does not. How to keep them in state without local Storage or cookies?
Any help would be greatly appreciated!
Basically, as Sang Đặng mentioned, if you want to have user data in your vuex (without storing it on the user side) you need to fetch them after every refresh. Refreshing the page means that whole Vue application (and your Vuex state) is removed from the memory (user's browser), which causes that you lose your current store data. token is also removed from the memory, but you load it on your store initialisation:
state: {
token: localStorage.getItem('token'),
...
}
Because of this you are seeing token "kept" in store, while other user data not. There are many ways to fetch user data after refresh - like mentioned beforeRouteEnter. Basically if you want to fetch them on the application load, so you can use Vue.created hook for example. You can also use lazy-loading in your getUser method - if there is no user data - fetch them from your API. Here you can read more about authentication patterns in SPA - for example using OAuth.

How do correctly add a getter to a Vuex Module?

I'm trying to create a Vuex module whenever I register the module, I get a state is undefined, even though there is nothing calling the getter I had just made. I'm able to call actions correctly with no errors.
This is my module. customer.js
export default {
namespaced: true,
state: {
login: false,
},
getters: {
isLoggedIn: (state) => {
console.log(state);
state.login;
}
},
mutations: {
set_login: (state, login) => {
state.login = login;
},
set_orders: (state, orders) => {
state.orders = orders;
},
},
actions: {
newsletter_subscribe: (context, email) => {
//- TODO
},
}
}
I have register via the registerModule function.
import Customer from './customer';
store.registerModule('customer', Customer, {
preserveState: true
});
Whenever I have developer tools open it just alerts me that.
Uncaught ReferenceError: state is not defined
at isLoggedIn (customer.js:11)
at wrappedGetter (vuex.esm.js:734)
Am I doing anything wrong with my getter?
I've only noticed the getter being called with Vue Dev tools open as I tried putting an alert in the getter to see what else could be triggering without the state being passed in.
I managed to solve it by giving my store a blank state!
const store = new Vuex.Store({
state: {}
});
And registering modules as normal.