I want to return a value from mutation to action.
I this case, I want the last inserted object :
In my mutation, work fine :
mutations: {
insert(state, item) {
const guid = Math.floor(Math.random() * 6) + 1; // any sense, just example
item.guid = guid;
state.data.push(item);
return guid;
},
},
In my action, work fine for the call, not for the return :
actions: {
insert ({ commit }, data) {
return new Promise((resolve) => {
const guid = commit('insert', event);
resolve(guid); // resolve undefined
});
},
},
There is a way to return the guid ?
I need it to emit after with my component...
Thanks
Mutations (commits) don't return values.
And, as mentioned in comments, the best practice is to leave such GUID generation computation to an action and just really commit the state in the mutation.
That being said, you cand send a callback to the mutation and call it. Just make sure the callback code is simple and synchronous (if not, see below).
const store = new Vuex.Store({
strict: true,
state: {
data: []
},
mutations: {
insert(state, {item, callback}) {
const guid = Math.floor(Math.random() * 600) + 1; // any sense, just example
item.guid = guid;
state.data.push(item);
callback(guid);
},
},
actions: {
insert ({ commit }, data) {
return new Promise((resolve) => {
commit('insert', {item: data, callback: resolve});
});
},
},
});
new Vue({
store,
el: '#app',
data: { insertedGuid: 'click button below' },
methods: {
go: async function() {
const guid = await this.$store.dispatch('insert', {name: "Alice"});
this.insertedGuid = guid;
}
},
computed: {
datadata: function() {
return this.$store.state.data
}
},
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app">
<p>store's data: {{ datadata }}</p>
<p>insertedGuid: {{ insertedGuid }}</p>
<button #click="go">Click to Insert</button>
</div>
If you have no idea of what the callback could be, I suggest you wrap it as
setTimeout(() => callback(guid));
Which would end the mutation right away and send the callback execution later down the queue of the event loop.
you can access the state data by passing it into the action insert ({ commit, state }, data) { ...
example:
actions: {
insert ({ commit, state }, data) {
return new Promise((resolve) => {
commit('insert', event);
const guid = state.data[state.data.length].guid
resolve(guid); // resolve undefined
});
},
},
Related
I have two functions in my store, one that gets data by calling API and one that toggles change on cell "approved". Everything working fine, except that when I toggle this change it happens in database and I get the response that it is done but It doesn't update on UI.
I am confused, what should I do after toggling change to reflect change on UI, should I call my API from .then or should I call action method responsible for getting data from server.
export default {
state: {
drivers: {
allDrivers:[],
driversError:null
},
isLoading: false,
token: localStorage.getItem('token'),
driverApproved: null,
driverNotApproved: null
},
getters: {
driversAreLoading (state) {
return state.isLoading;
},
driverError (state) {
return state.drivers.driversError;
},
getAllDrivers(state){
return state.drivers.allDrivers
}
},
mutations: {
getAllDrivers (state) {
state.isLoading=true;
state.drivers.driversError=null;
},
allDriversAvailable(state,payload){
state.isLoading=false;
state.drivers.allDrivers=payload;
},
allDriversNotAvailable(state,payload){
state.isLoading=false;
state.drivers.driversError=payload;
},
toggleDriverApproval(state){
state.isLoading = true;
},
driverApprovalCompleted(state){
state.isLoading = false;
state.driverApproved = true;
},
driverApprovalError(state){
state.isLoading = false;
state.driverError = true;
}
},
actions: {
allDrivers (context) {
context.commit("getAllDrivers")
return new Promise((res,rej)=>{
http.get('/api/admin/getAllDrivers').then(
response=>{
if (response.data.success){
let data=response.data.data;
data=data.map(function (driver) {
return {
/* response */
};
});
context.commit("allDriversAvailable",data);
res();
}else {
context.commit("allDriversNotAvailable",response.data)
rej()
}
})
.catch(error=>{
context.commit("allDriversNotAvailable",error.data)
rej()
});
});
},
toggleDriverApproval (context, payload){
return new Promise((res, rej)=>{
http.post("/api/admin/toggleDriverApproval",{
driver_id: payload
})
.then( response => {
context.commit('driverApprovalCompleted');
res();
}).catch( error =>{
context.commit('driverApprovalError');
rej()
})
})
}
}
}
and here is the code on the view, I wrote the necessary code for better clarification of the problem
export default {
name: 'Drivers',
data: () => ({
data: [],
allDrivers: [],
driversErrors: []
}),
created() {
this.$store
.dispatch('allDrivers')
.then(() => {
this.data = this.$store.getters.getAllDrivers
})
.catch(() => {
this.errors = this.$store.getters.driverError
})
},
computed: {
isLoading() {
return this.$store.getters.driversAreLoading
}
},
methods: {
verify: function(row) {
console.log(row)
this.$store.dispatch('toggleDriverApproval', row.id).then(() => {
this.data = this.$store.getters.getAllDrivers
console.log('done dis')
})
},
},
}
if I understand your issue, you want the UI displaying your data to change to the updated data after making a post request.
If you are using Vuex you will want to commit a mutation, and use a getter display the data.
I am not sure how your post request is being handled on the server but if successful typically you would send a response back to your front end with the updated data, and commit a mutation with the updated data.
Example:
Make a Post request
toggleDriverApproval (context, payload){
return new Promise((res, rej)=>{
http.post("/api/admin/toggleDriverApproval",{
driver_id: payload
})
.then( response => {
context.commit('driverApprovalCompleted', response.data);
res();
}).catch( error =>{
context.commit('driverApprovalError', error.response.data);
rej()
})
})
}
If succesful commit the mutation
.then( response => {
context.commit('driverApprovalCompleted', response.data);
res();
})
response.data being your data you want to mutate the state with.
Mutation Example:
customMutation(state, data) {
state.driverApproval = data
}
Getter Example:
driver(state) {
return state.driverApproval
}
displaying the getter in a template
<template>
<div v-if="driver">{{driver}}</div>
</template>
<script>
import {mapGetters} from 'vuex'
export default {
name: Example,
computed: {
driver() {
return this.$store.getters.driver
},
// or use mapGetters
...mapGetters(['driver'])
}
}
</script>
more examples can be found at Vuex Docs
I'm new to Vue.js and Vuex and trying out a sample app.
This is the scenario-
I have a store module for notifications which stores the notifications in an object with a given name as its key.
{
'message1': {
type: 'info',
message: 'This is an info message.',
isShown: true,
},
'message2': {
type: 'success',
message: 'This is a success message.',
isShown: true,
},
'message3': {
type: 'error',
message: 'This is an error message.',
isShown: true,
}
}
And this is my Vuex module that handles notification-
const state = {
notifications: {},
};
const mutations = {
setNotification(state, { message, type, name }) {
state.notifications[name] = {
message,
type,
isShown: true,
}
},
removeNotification(state, name) {
delete state.notifications[name];
}
};
const actions = {
async showNotification(context, options) {
await context.commit('setNotification', options);
},
async removeNotification(context, name) {
await context.commit('removeNotification', name);
}
}
const getters = {
isNotificationShown: (state, getters) => {
return getters.getNotificationMessageList.length > 0;
},
getNotificationMessageList: state => {
return state.notifications;
},
}
export default {
state,
actions,
mutations,
getters,
}
And this is my component-
<template>
<div v-if="isShown">
<div v-for="(notice, name, index) in notificationMessageList" :key="name">
{{ index }} - {{ notice.type }} - {{ notice.message}}
</div>
</div>
</template>
<script>
export default {
computed: {
isShown() {
return this.$store.getters.isNotificationShown;
},
notificationMessageList() {
return this.$store.getters.getNotificationMessageList;
},
},
};
</script>
I checked with the Vue Development tool and found that the store does get updated and so does the component with the notification messages that I'm passing to the store. But the component is not being rendered. But if I use the same data by hardcoding it in the component, it works.
I'm not sure if this is the right way to connect the Vuex store to a component.
It's Vue reactivity problem. You need to update the reference to make Vue reactive. You can use JSON.parse(JSON.stringify()) or use ES6 syntax:
const mutations = {
setNotification(state, { message, type, name }) {
state.notifications = {
...state.notifications,
[name]: {
message,
type,
isShown: true
}
}
},
removeNotification(state, name) {
const newNotifications = {...state.notifications}
delete newNotifications[name]
state.notifications = newNotifications
}
};
In the documentation, it is written that the state is immutable apart from the mutations called via the actions ... Ok.
I use in my component, mapGetters, mapActions ...
store :
export default {
namespaced: true,
state: {
color: "violet"
},
mutations: {
changeColor(state, newColor) {
state.color = newColor
},
},
actions: {
changeColor({ commit }, newColor) {
commit('changeColor', newColor)
}
}
component :
...
methods: {
...mapActions({
setColor: 'store/changeColor',
}),
myMethodCallByButton(){
this.setColor("blue").then(response => {
console.log("change Color done")
},err => {
console.log("change Color error")
})
}
...
The method works fine, the store is updated, EXCEPT that I never receive the console.log ().
It is written in the documentation that mapActions were equivalent to this.$store.dispatch.
Why do not I get the message?
Is there another solution ?
PS: I want to keep the mapGetters map, mapActions .. I do not like calling this.$store.dispatch
PS2: I work with modules in my store
Thank you
Every Vuex action returns a Promise.
Vuex wraps the results of the action functions into Promises. So the changeColor action in:
actions: {
changeColor({ commit }, newColor) {
myAsyncCommand();
}
}
Returns a Promise that resolves to undefined and that will not wait for the completion myAsyncCommand();'s asynchronous code (if it doesn't contain async code, then there's no waiting to do).
This happens because the code above is the same as:
changeColor({ commit }, newColor) {
myAsyncCommand();
return undefined;
}
And when .dispatch('changeColor', ...) Vuex will then return Promise.resolve(undefined).
If you want the Promise returned by the action to wait, you should return a Promise that does the property waiting yourself. Something along the lines of:
changeColor({ commit }, newColor) {
return new Promise((resolve, reject) => {
myAsyncCommand().then(resolve);
});
// or, simply: return myAsyncCommand();
}
Demo implementation below with more details:
const myStore = {
namespaced: true,
state: { color: "violet" },
mutations: {
changeColor(state, newColor) {
state.color = newColor
}
},
actions: {
changeColor_SIMPLE({ commit }, newColor) {
commit('changeColor', newColor)
},
changeColor_COMPLICATED_NO_PROMISE({ commit }, newColor) {
setTimeout(() => {
commit('changeColor', newColor)
}, 2000)
},
changeColor_COMPLICATED_WITH_PROMISE({ commit }, newColor) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('changeColor', newColor)
resolve();
}, 2000)
});
}
}
};
const store = new Vuex.Store({
modules: {
store: myStore,
}
});
new Vue({
store,
el: '#app',
methods: {
...Vuex.mapActions({
setColorSimple: 'store/changeColor_SIMPLE',
setColorComplicatedNoPromise: 'store/changeColor_COMPLICATED_NO_PROMISE',
setColorComplicatedWithPromise: 'store/changeColor_COMPLICATED_WITH_PROMISE',
}),
myMethodCallByButton(){
this.setColorSimple("blue")
.then(response => console.log("SIMPLE done"),err => console.log("SIMPLE err"));
this.setColorComplicatedNoPromise("blue")
.then(response => console.log("NO_PROMISE done"),err => console.log("NO_PROMISE err"));
this.setColorComplicatedWithPromise("blue")
.then(response => console.log("WITH_PROMISE done"),err => console.log("WITH_PROMISE err"));
}
}
})
<script src="https://unpkg.com/vue#2.5.16/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app">
<p>color: {{ $store.state.store.color }}</p>
<button #click="myMethodCallByButton">click me and WAIT for 2s</button>
</div>
Update/Per comments:
Even if the mapAction / dispatch returns a promised, I am in my case obliged to add a promise to wait for the end of the "mutation". I thought, from the documentation, that it was precisely managed via the mapAction. Is it exact?
If an action calls a mutation only, such as:
actions: {
changeColor({ commit }, newColor) {
commit('changeColor', newColor)
return undefined; // added for clarity
}
}
Then the returned Promise will only execute after the commit() completes.
That does not happen because Vuex manages waiting of mutations (commits).
It happens that way because there's no waiting to do. This is because Vuex requires: mutations must be synchronous operations.
Since mutations are synchronous, the line of the return above will only execute after the code of the line before (commit('changeColor', newColor)).
Note: If your mutations have asynchronous code, you should make them synchronous, as it goes against how Vuex properly works and may yield all kinds of unexpected behaviors.
I tried the syntax given in vuex doc.
store.state.a // -> moduleA's state
store.state.b // -> moduleB's state
app.js
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('task-index', require('./components/TaskList.vue'));
Vue.component('task-show', require('./components/TaskShow.vue'));
Vue.component('note-index', require('./components/NoteList.vue'));
Vue.component('note-show', require('./components/NoteShow.vue'));
const notes = {
state: {
edit: false,
list:[],
note: {
note : '',
id : ''
}
},
mutations: {
SET_EDIT: (state, data) => {
state.edit = data
},
SET_LIST: (state, data) => {
state.list = data
},
SET_NOTE: (state, data) => {
state.note.id = data.id;
state.note.note = data.note;
},
SET_EMPTY: (state) => {
state.note.note = '';
}
},
getters: {
noteCount: (state) => state.list.length
},
actions : {
getNote: ({commit,state}) => {
axios.get('/api/note/list')
.then((response) => {
commit('SET_LIST', response.data);
commit('SET_EDIT',false);
commit('SET_EMPTY');
})
},
}
};
const tasks = {
state: {
edit: false,
list:[],
task: {
body : '',
id : ''
}
},
mutations: {
SET_EDIT: (state, data) => {
state.edit = data
},
SET_LIST: (state, data) => {
state.list = data
},
SET_TASK: (state, data) => {
state.task.id = data.id;
state.task.body = data.body;
},
SET_EMPTY: (state) => {
state.task.body = '';
}
},
getters: {
taskCount: (state) => state.list.length
},
actions : {
getTask: ({commit,state}) => {
axios.get('/api/task/list')
.then((response) => {
commit('SET_LIST', response.data);
commit('SET_EDIT',false);
commit('SET_EMPTY');
})
},
}
};
const store = new Vuex.Store({
modules : {
task : tasks,
note : notes
}
});
const app = new Vue({
el: '#app',
store
});
TaskList.vue
<template>
<div >
<h4>{{count}} Task(s)</h4>
<ul class="list-group">
<li class="list-group-item" v-for="item in list">
{{item.body}}
<button class="btn btn-primary btn-xs" #click="showTask(item.id)">Edit</button>
<button class="btn btn-danger btn-xs" #click="deleteTask(item.id)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
export default{
computed :{
list() {
return this.$store.state.task.list;
},
count(){
return this.$store.getters.taskCount;
}
},
mounted(){
this.$store.dispatch('getTask');
},
methods : {
showTask: function(id){
axios.get('/api/task/'+ id)
.then(response => {
this.$store.commit('SET_TASK',response.data);
this.$store.commit('SET_EDIT',true);
});
},
deleteTask: function(id){
axios.delete('/api/task/delete/' + id)
this.$store.dispatch('getTask');
}
}
}
</script>
I'am getting "Uncaught TypeError: Cannot read property 'task' of undefined " in this line of code 'return this.$store.state.task.list;'
acoording to documentation of vuex
By default, actions, mutations and getters inside modules are still
registered under the global namespace
so you can only use getters in vuex root context.
Well, the state you're trying to retrieve doesn't match the structure of your state:
state: {
edit: false,
list:[],
note: {
note : '',
id : ''
}
},
If you change this.$store.state.task.list to this.$store.state.list then you should be all patched up.
I am using Vue.js 2.0 and Vuex 2.0 for a small app. I am initializing the store in the 'created' life-cycle hook on the root Vue instance by calling an action that retrieves the initial state from an API....like so in my Root Component:
const app = new Vue({
el: "#app",
router,
store,
data: {
vacation: {},
},
components: {
'vacation-status': VacationStatus,
},
created() {
//initialize store data structure by submitting action.
this.$store.dispatch('getVacation');
},
computed: {},
methods: {}
});
This is working just fine. Here is the action on my store that I'm calling here:
getVacation({ commit }) {
api.getVacation().then(vacation => commit(UPDATE_VACATION, vacation))
}
The mutation that this is committing with 'UPDATE_VACATION' is here:
[UPDATE_VACATION] (state, payload) {
state.vacation = payload.vacation;
},
My Problem: When I load the app, all my components that are 'getting' values from the store throw errors I'm trying to access 'undefined' values on the store. In other words, state hasn't been initialized yet.
For example, I have a component that has getters in Child Components like this:
computed: {
arrival() {
return this.$store.getters.arrival
},
departure() {
return this.$store.getters.departure
},
countdown: function() {
return this.$store.getters.countdown
}
}
All these getters cause errors because 'vacation' is undefined on the state object. It seems like an asynchronous problem to me, but could be wrong. Am I initializing my store state in the wrong spot?
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
getters: {
getVacation: state => {
return state.vacation
},
guests: state => {
return state.vacation.guests
},
verifiedGuests: state => {
return state.vacation.guests.filter(guest => guest.verified)
},
emergencyContacts: state => {
return state.emergency_contacts
},
arrival: state => {
return state.vacation.check_in
},
departure: state => {
return state.vacation.check_out
},
countdown: state => {
let check_in = new Date(state.vacation.check_in);
let now = new Date();
if ((now - check_in) > 0) {
return 'This vacation started on ' + check_in;
}
let difference = check_in - now;
let day = 1000 * 60 * 60 * 24;
return Math.ceil(difference / day) + " days until your vacation";
}
},
mutations: {
[UPDATE_VACATION](state, payload) {
state.vacation = payload.vacation;
},
[ADD_GUEST](state, payload) {
state.vacation.guests.push(payload.guest);
},
[REMOVE_GUEST](state, payload) {
state.vacation.guests.filter(guest => {
debugger;
return guest.id != payload.guest.id
})
},
[UPDATE_GUEST](state, payload) {
state.vacation.guests.map(guest => {
// Refactor Object.assign to deep cloning of object
return guest.id === payload.guest.id ? Object.assign({}, guest, payload.guest) : guest;
})
},
[ADD_EMERGENCY](state, payload) {
state.vacation.emergency_contacts.push(payload.emergency_contact)
},
[REMOVE_EMERGENCY](state, payload) {
state.vacation.emergency_contacts.filter(contact => contact.id !== payload.emergency_contact.id)
},
[UPDATE_EMERGENCY](state, payload) {
state.vacation.emergency_contacts.map(contact => {
// Refactor not needed because emergency_contact is a shallow object.
return contact.id === payload.emergency_contact.id ? Object.assign({}, contact, payload.emergency_contact) : contact;
});
}
},
actions: {
getVacation({
commit
}) {
api.getVacation().then(vacation => commit(UPDATE_VACATION, vacation))
},
addGuest({
commit
}, guest) {
commit(ADD_GUEST, guest);
},
removeGuest({
commit
}, guest) {
commit(REMOVE_GUEST, guest);
},
updateGuest({
commit
}, guest) {
commit(UPDATE_GUEST, guest);
},
addEmergency({
commit
}, guest) {
commit(ADD_EMERGENCY, contact)
},
removeEmergency({
commit
}, contact) {
commit(REMOVE_EMERGENCY, contact)
},
updateEmergency({
commit
}, contact) {
commit(UPDATE_EMERGENCY, contact)
},
updateServer(store, payload) {
return api.saveVacation(payload)
}
}
});
Just so the solution is clear to others:
I wasn't setting my initial state quite properly in the store itself. I was pulling in the data, and updating the store correctly, but the store needed to be initialized like this:
export default new Vuex.Store({
state: {
vacation: {} //I added this, and then justed updated this object on create of the root Vue Instance
},
});
I think you're doing everything right. Maybe you're just not creating the getters correctly (can't see any definition in your code). Or your setting the initial state not correctly (also not visible in your snippet).
I would use mapState to have the state properties available in components.
In the demo simply add users to the array in mapState method parameter and the users data will be available at the component. (I've just added the getter users to show how this is working. That's not needed if you're using mapState.)
Please have a look at the demo below or this fiddle.
const api =
'https://jsonplaceholder.typicode.com/users'
const UPDATE_USERS = 'UPDATE_USERS'
const SET_LOADING = 'SET_LOADING'
const store = new Vuex.Store({
state: {
users: {},
loading: false
},
mutations: {
[UPDATE_USERS](state, users) {
console.log('mutate users', users)
state.users = users;
console.log(state)
}, [SET_LOADING](state, loading) {
state.loading = loading;
}
},
getters: {
users(state) {
return state.users
}
},
actions: {
getUsers({commit}) {
commit(SET_LOADING, true);
return fetchJsonp(api)
.then((users) => users.json())
.then((usersParsed) => {
commit(UPDATE_USERS, usersParsed)
commit(SET_LOADING, false)
})
}
}
})
const mapState = Vuex.mapState;
const Users = {
template: '<div><ul><li v-for="user in users">{{user.name}}</li></ul></div>',
computed: mapState(['users'])
}
new Vue({
el: '#app',
store: store,
computed: {
...mapState(['loading']),
//...mapState(['users']),
/*users () { // same as mapState
return this.$store.state.users;
}*/
users() { // also possible with mapGetters(['users'])
return this.$store.getters.users
}
},
created() {
this.$store.dispatch('getUsers')
},
components: {
Users
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch-jsonp/1.0.5/fetch-jsonp.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.1.1/vuex.min.js"></script>
<div id="app">
<div v-if="loading">loading...</div>
<users></users>
<pre v-if="!loading">{{users}}</pre>
</div>
You can create a function that returns the initial state, and use it into your Vuex instance, like this:
function initialStateFromLocalStorage() {
...
const empty = {
status: '',
token: '',
user: null
}
return empty;
}
export default new Vuex.Store({
state: initialStateFromLocalStorage,
...
As soon as you return an object for the state, you can do whatever you want inside that function, right?