I'm trying to get this informations and put it in "user" :
the action in VueJS:
export default new Vuex.Store({
state: {
status: '',
token: localStorage.getItem('token') || '',
user : {},
test : []
},
mutations: {
auth_request(state){
state.status = 'loading'
},
auth_success(state, token, user){
state.status = 'success'
state.token = token
state.user = user
},
auth_error(state){
state.status = 'error'
},
logout(state){
state.status = ''
state.token = ''
},
},
actions: {
login({commit}, user){
return new Promise((resolve, reject) => {
commit('auth_request')
axios.get('http://localhost:8080/offreeduwar/api/Useraccount/login/'+ user.email+'/'+user.password)
.then((resp) => {
const token = resp.data.token
const user = resp.data
console.log(test)
localStorage.setItem('token', token)
// Add the following line:
axios.defaults.headers.common['Authorization'] = token
commit('auth_success', token, user)
resolve(resp)
})
.catch(err => {
commit('auth_error')
localStorage.removeItem('token')
reject(err)
})
})
},
But all the time in Vue devtool : the state of user is empty , so the question how to put this informations in user to work with this variable
The commit method in the store has two parameters: the name of the mutation and the params (if it is of a primitive type, the value itself, if it is an object, then an object). So you should try it like this:
commit('auth_success', { token, user })
and then:
auth_success(state, payload){
state.status = 'success'
state.token = payload.token
state.user = payload.user
},
Related
I am unable to store the data from the API in the state, is there any issue in my code?
I am not able to console.log(state.token) or state.token from the mutations.
My Store
export const AUTH_MUTATIONS = {
SET_USER: 'SET_USER',
SET_PAYLOAD: 'SET_PAYLOAD',
LOGOUT: 'LOGOUT',
}
export const state = () => ({
token: null,
userdata: [],
data: [],
})
export const mutations = {
[AUTH_MUTATIONS.SET_USER] (state, { userdata }) {
state.userdata = userdata
},
[AUTH_MUTATIONS.SET_PAYLOAD] (state, { token }) {
state.token = token
},
}
export const actions = {
async login ({ commit, dispatch }, { email_id, password }) {
const { data: {data: { user, token } } } = await this.$axios.post('http://18.xxx.246.xxx:5000/api/v1/users/login',
{
email_id,
password
})
// console.log(user)
// console.log(token)
commit(AUTH_MUTATIONS.SET_USER, user)
commit(AUTH_MUTATIONS.SET_PAYLOAD, token)
// console.log(AUTH_MUTATIONS.SET_USER, user)
},
}
export const getters = {
isAuthenticated: (state) => {
return state.token && state.token !== ''
},
}
In your action you need to take in state in the destructured parameters like this: { commit, dispatch, state } then you will be able to access your state and log state.token.
If it's still null after that point then you should debug it to ensure that you're setting it correctly in the mutation itself.
I am trying to make an api call in login and I want to store it in Vuex store. So in the beginning my mutation:
export const STORE_USER = (state, {user}) => {
state.user = user;
}
and my action:
export const storeUser = ({commit}, {user}) => {
commit('STORE_USER', {user});
}
So as you see after login, I want to make an api call and get the user information. I want to this user information in Vuex store but it comes empty.
So I am expecting the state that you see above should be filled after login. My login component is:
export default {
name: 'Login',
mounted() {
EventBus.$on(GENERAL_APP_CONSTANTS.Events.CheckAuthentication, () => {
this.authenticated = authHelper.validAuthentication();
this.cookie = cookieHelper.getCookie(this.cookieName);
this.cookieValue = cookieHelper.getCookieValue(this.cookie);
if (this.authenticated) {
this.email = this.password = "";
this.authenticationFailed = false;
this.storeUser();
}
});
EventBus.$on(GENERAL_APP_CONSTANTS.Events.LoginFailed, () => {
this.authenticationFailed = true
});
},
data () {
return {
authenticated: false,
authenticationFailed: false,
email: '',
password: '',
rememberMe: false,
cookieName: "_token",
cookie: "",
cookieValue: "",
}
},
methods: {
signIn: function () {
authHelper.signIn(this.email, this.password, () => {
this.$router.push({name: 'home'});
});
},
storeUser: function () {
apiHelper.getRequest(
`/users/${cookieHelper.parseJwt(this.cookieValue).user_id}`,
(response) => {
this.$store.dispatch('storeUser', {
user: response.data,
})
}
)
},
}
}
So why do you think the in-store user Object is empty? Because I response.data is not empty either. Please let me know.
I've recently learnt a bit about vuex and store.
I was about to use it for calling my api but it keeps saying my
url is undefined.
here is my vuex codes:
import { createStore } from 'vuex'
import axios from "axios";
const url = 'https://myurl'
export default createStore({
state: {
catList: [],
transactList: [],
user: [],
requestList: [],
catInList: [],
productList: [],
errorMs: '',
calling: false,
mobile: ''
},
getters: {
allUsers: (state) => state.user,
transactList: (state) => state.transactList,
categoryList: (state) => state.catList,
requestList: (state) => state.requestList,
productList: (state) => state.productList,
},
mutations: {
SET_Users (state, user) {
state.user = user
}
},
actions: {
checkAuth() {
const token = localStorage.getItem('token') ? localStorage.getItem('token') : ''
axios.defaults.baseURL = url
axios.defaults.headers.common['Authorization'] = token ? `Bearer ${token}` : ''
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
},
async axiosPost ({dispatch} ,{url}) {
dispatch('checkAuth')
await axios.post(url+'/login', {
mobile: this.mobile
}).then(response => {
this.calling = false
localStorage.setItem('token', response.data.token)
})
},
async axiosGet ({dispatch} , {url, formData}) {
dispatch('checkAuth')
await axios.get(url, formData).catch(err => {
console.log(err)
})
}
},
created() {
}
})
actually I wanted to define my api globally, so that I can use it for different components only by adding url + '/login' but I'm not sure why it keeps saying my url is not defined.
can anyone help me with the errors?
I have a problem calling the action from vuex. Everytime I try to access the loginUser action I get an error 'unknown action type' from vuex. maybe I'm not calling it the right way. Please tell me what's wrong with my code.
store: user.js
import axios from 'axios'
export const state = () => ({
users: [],
loggedIn: false,
})
export const getters = {
getLoggedIn: (state) => { return state.loggedIn },
}
export const actions = {
loginUser({ commit }, payload){
if(state.loggedIn){
console.log("you're already logged in!")
}else{
return new Promise(async(resolve, reject) => {
const { data } = await axios.post('/api/users/login-admin', {
login: payload.login,
password: payload.password
})
if(data.success){
commit("loggedIn", true)
resolve()
}else{
commit("loggedIn", false)
reject('an error has ocurred')
}
return data.success
}).catch(err => alert(errCodes(err.code)))
}
},
}
export const mutations = {
setLoggedIn(state, payload) {
state.loggedIn = payload
}
}
login.vue
computed: {
...mapGetters(['getCount'] , {user: 'getLoggedIn'}),
...mapActions([
'loginUser'
]),
},
methods: {
onSubmit: function(){
this.$store.dispatch({
type: 'loginUser',
email: this.login,
pass: this.pass
}).then(()=>{
this.$router.push('../admin_2065')
this.onReset()
}).catch(e => console.log(e))
},
onReset(){
this.login = ''
this.pass = ''
this.$nextTick().then(() => {
this.ready = true
})
}
},
error:
any help will be appreciated, thanks.
mapActions should be inside the methods option and add the namespace user/ :
computed: {
...mapGetters(['getCount'] , {user: 'getLoggedIn'}),
},
methods: {
...mapActions([
'user/loginUser'
]),
onSubmit: function(){
this['user/loginUser']({
email: this.login,
pass: this.pass
}).then(()=>{
this.$router.push('../admin_2065')
this.onReset()
}).catch(e => console.log(e))
},
onReset(){
this.login = ''
this.pass = ''
this.$nextTick().then(() => {
this.ready = true
})
}
},
I'm trying to implement authentication in vuejs 3. I'm django and django as a backend and simple jwt for generating token. Every things is working fine. Generated token are in this format.
And here is my auth store , by the way I'm using axios and vuex
import axios from "axios";
import { API_ENDPOINTS } from "../../constants/API";
const authStore = {
state: {
status: "",
access_token: localStorage.getItem("access_token") || "",
refresh_token: localStorage.getItem("refresh_token") || "",
},
mutations: {
auth_request(state) {
state.status = "loading";
},
auth_success(state, access_token, refresh_token, user) {
state.status = "success";
state.access_token = access_token;
state.refresh_token = refresh_token;
state.user = user;
},
auth_error(state) {
state.status = "error";
},
logout(state) {
state.status = "";
state.access_token = "";
state.refresh_token = "";
},
},
actions: {
login({ commit }, user) {
return new Promise((resolve, reject) => {
commit("auth_request");
axios({
url: API_ENDPOINTS.CREATE_TOKEN,
data: user,
method: "POST",
})
.then((resp) => {
console.log(resp);
const access_token = resp.data.access;
const refresh_token = resp.data.refresh;
const user = resp.data.user;
localStorage.setItem("access_token", access_token);
localStorage.setItem("refresh_token", refresh_token);
axios.defaults.headers.common[
"Authorization"
] = `Bearer ${access_token}`;
commit("auth_success", access_token, refresh_token, user);
resolve(resp);
})
.catch((err) => {
commit("auth_error");
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
reject(err);
});
});
},
logout({ commit }) {
// eslint-disable-next-line no-unused-vars
return new Promise((resolve, reject) => {
commit("logout");
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
delete axios.defaults.headers.common["Authorization"];
resolve();
});
},
},
getters: {
isLoggedIn: (state) => !!state.access_token,
authStatus: (state) => state.status,
},
};
export default authStore;
Above code is working fine, only issue is that whenever I refresh my page, I can't able to perform any operation, Like get or post.
Even token is available in localstorage.
Note:-
I think I'm missing some things like refresh token, I think i need to use refresh token, but I've no any idea that how can i use refresh token if refresh token is problem.
axios.defaults.headers.common[
"Authorization"
] = `Bearer ${access_token}`;
This code is noly called when user login, so maybe you should call it when the token is availble at localstorage.