Reputation: 23
I am using vuex and I have index.js and auth.js in store folder. I want a basic sign in operation in my signin.vue with calling action from store but I got that error 'Uncaught (in promise) ReferenceError: dispatch is not defined' while I am calling action from another action with dispatch key in auth.js.
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import auth from './auth'
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {
auth
}
})
auth.js
import axios from "axios";
export default {
namespaced: true,
state: {
token: null,
user: null
},
mutations: {
SET_TOKEN(state, token) {
state.token = token;
},
SET_USER(state, data) {
state.user = data;
}
},
actions: {
async signIn(_, credentials) {
let response = await axios.post("auth/signin", credentials)
/* eslint-disable */
dispatch('attempt', response.data.token);
},
async attempt({commit}, token) {
commit("SET_TOKEN", token);
try {
let response = await axios.get('auth/me', {
headers: {
'Authorization': 'Bearer ' + token
}
});
commit("SET_USER", response.data)
} catch (e) {
commit("SET_TOKEN", null);
commit("SET_USER", null);
}
}
}
}
SignIn.vue
<template>
<div>
<form @submit.prevent="submit">
<div>
<label for="email">Email</label>
<input id="email" type="email" name="email" v-model="form.email">
</div>
<div>
<label for="password">Password</label>
<input id="password" type="password" name="password" v-model="form.password">
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
</template>
<script>
import {mapActions} from "vuex";
export default {
name: "signIn",
data() {
return {
form: {
email: "",
password: ""
}
}
},
methods: {
...mapActions({
signIn: 'auth/signIn'
}),
submit() {
this.signIn(this.form)
}
}
}
</script>
Upvotes: 0
Views: 1182
Reputation: 195
async attempt({commit}, token) like this you have to do write dispatch {dispatch} in async signIn() function.
i.e. async attempt({dispatch}, token)
I think this may work! :)
Upvotes: 1