VueJs + Vuex + mapActions - vuejs2

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.

Related

Unabled to use Vuex Getter with params

I have Vuex Store that will look like this
const config = {
featureA: { isEnabled: true, maxUser: 2 },
featureB: { isEnabled: false, maxData: 5 },
}
const actions = {
getDataCompany(context, payload) {
return new Promise(async (resolve, reject) => {
try {
const result = await firebase.firestore().collection(payload.collection).doc(payload.companyId).get()
if (result) {
if (payload.isLogin) await context.commit('setConfig', result.data())
return resolve(result.data())
}
reject(new Error('Fail To Load'))
} catch (e) {
reject(new Error('Connection Error'))
}
})
}
}
const mutations = {
setConfig(state, payload) {
state.config = payload
}
}
const getters = {
getData: ({ config }) => (feature, key) => {
const state = config
if (state) if (state[feature]) if (state[feature][key]) return state[feature][key]
return null
}
}
export default new Vuex.Store({
state: { config },
actions: { ...actions },
mutations: { ...mutations },
getters: { ...getters }
})
It's working fine with this method to get the data
computed: {
featureAEnabled() {
return this.$store.getters.getData('featureA', 'isEnabled')
},
}
But I have a problem when the data is change, the value is not update in component, and now I want to use mapGetters because it say can detect changes, But I have problem with the documentation and cannot find how to pass params here,
import { mapGetters } from 'vuex'
computed: {
...mapGetters({
featureAEnabled: 'getData'
})
}
I'am calling the action from here
async beforeMount() {
await this.$store.dispatch('getDataCompany', {collection: 'faturelsit', companyId: 'asep', isLogin: true})
}
And try to detect change in here
mounted() {
if (this.featureAEnabled) console.log('feature enabled')
}
The value change is not detected, and need to refresh twice before the changes is implemented in component
My main target is to detect if there any data change in Vuex and make action in component,
nevermind just working with watch without mapgetter,
I just realize that computed cannot re-run the mounted, so I make method that will called when the variable change in watch. thank you.
The main purpose is fulfilled, but the mapgetter with params is still not answered. so if anyone want to answer please share the way to use mapgetter with params.
You could try to use get and set methods for your computed property.
Example:
computed: {
featureAEnabled: {
get() {
return this.$store.getters.getData('featureA', 'isEnabled')
},
set(value) {
...update featureEnabled property in vuex store
}
},
}

Vuex update state by using store actions

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

Vue - Data not computed in time before mount

I'm learning Vue and I've run into a problem where my data returns undefined from a computed method. It seems that the data is not computed by the time the component is mounted, probably due to the get request - wrapping my this.render() in a setTimeout returns the data correctly. Setting a timeout is clearly not sensible so how should I be doing this for best practice?
Home.vue
export default {
created() {
this.$store.dispatch('retrievePost')
},
computed: {
posts() {
return this.$store.getters.getPosts
}
},
methods: {
render() {
console.log(this.comments)
}
},
mounted() {
setTimeout(() => {
this.render()
}, 2000);
},
}
store.js
export const store = new Vuex.Store({
state: {
posts: []
},
getters: {
getPosts (state) {
return state.posts
}
},
mutations: {
retrievePosts (state, comments) {
state.posts = posts
}
},
actions: {
retrievePosts (context) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token
axios.get('/posts')
.then(response => {
context.commit('retrievePosts', response.data)
})
.catch(error => {
console.log(error)
})
}
}
})
It is because axios request is still processing when Vue invokes mounted hook(these actions are independent of each other), so state.posts are undefined as expected.
If you want to do something when posts loaded use watch or better computed if it's possible:
export default {
created() {
this.$store.dispatch('retrievePost')
},
computed: {
posts() {
return this.$store.getters.getPosts
}
},
methods: {
render() {
console.log(this.comments)
}
},
watch: {
posts() { // or comments I dont see comments definition in vue object
this.render();
}
}
}
P.S. And don't use render word as methods name or something because Vue instance has render function and it can be a bit confusing.

Vuex Mutation return last inserted

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
});
},
},

Vuex rendering data that is fetched from REST API

For such component
<template>
<div>
<router-link :to="{name:'section', params: { sectionId: firstSectionId }}">Start</router-link>
</div>
</template>
<script lang="ts">
import { mapActions } from "vuex"
export default {
mounted() {
this.getSectionId()
},
computed: {
firstSectionId() {
return this.$store.state.firstSectionId
}
},
methods: mapActions(["getSectionId"])
}
</script>
Store:
const store: any = new Vuex.Store({
state: {
firstSectionId: null
},
// actions,
// mutations
})
I have a web request in the getSectionId action and it asynchronously fetches data and calls a mutation that will fill firstSectionId in state. During the initial rendering firstSectionId is null and I get the warning that a required parameter is missing during rendering of router-link.
It is not a problem here to add v-if="firstSectionId". But in general what is the approach for fetching data from a server to be displayed? Currently all my components are checking if there is data present in the store before rendering, is it normal or is there a better way to wait for data to be loaded before rendering it?
One approach for asynchronously fetching data is to use promise in vuex store actions.
Vue.http.get(API_URL)
.then((response) => {
//use response object
})
.catch((error) => {
console.log(error.statusText)
});
To demonstrate that I make request to this route. You can see how response should looks like. Let's save response object in state.users array.
store.js
const store = new Vuex.Store({
state: {
users: []
},
mutations: {
FETCH_USERS(state, users) {
state.users = users
}
},
actions: {
fetchUsers({ commit }, { self }) {
Vue.http.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
commit("FETCH_USERS", response.body);
self.filterUsers();
})
.catch((error) => {
console.log(error.statusText)
});
}
}
})
export default store
You noticed that there is self.filteruser() method after commit. That is crucial moment. Before that we are committing a mutation, which is synchronous operation and we are sure that we will have our response in store.state that can be used in filterUsers() method (don't forget to pass self parm)
Users.vue
import store from "../store/store"
export default {
name: 'users',
created() {
this.$store.dispatch("fetchUsers", { self: this })
},
methods:{
filterUsers() {
//do something with users
console.log("Users--->",this.$store.state.users)
}
}
}
Better ways (ES6 & ES7)
ES6 Promises for asynchronous programming
//User.vue
created() {
this.$store.dispatch("fetchUser").then(() => {
console.log("This would be printed after dispatch!!")
})
}
//store.js
actions: {
fetchUser({ commit }) {
return new Promise((resolve, reject) => {
Vue.http.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
commit("FETCH_USERS", response.body);
resolve();
})
.catch((error) => {
console.log(error.statusText);
});
});
}
}
ES7: async/await
To get away from callback hell, and to improve asynchronous programming use async function, and you can await on a promise. Code looks much easier to follow (like it is synchronous), but code isn't readable for browsers so you'll need Babel transpiler to run it.
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // wait for actionA to finish
commit('gotOtherData', await getOtherData())
}
}
In my experience, you can skip a few checks if you preset the state with an empty value of the same type as the expected result (if you know what to expect, of course), e.g. if you have an array of items, start with [] instead of null as it won't break v-for directives, .length checks and similar data access attempts.
But generally, adding v-if is a very normal thing to do. There's a section about this in the vue-router documentation and checking whether properties exist or not is exactly what it suggests. Another possible solution it mentions is fetching data inside beforeRouteEnter guard, which assures you will always get to the component with your data already available.
Ultimately, both solutions are correct, and the decision between them is more of a UX/UI question.
I had similar requirements for locations and the google map api. I needed to fetch my locations from the API, load them in a list, and then use those in a map component to create the markers. I fetched the data in a Vuex action with axios, loaded that in my state with a mutation, and then used a getter to retrieve the resulting array in the mounted life cycle hook. This resulted in an empty array as mounted fired before the async action resolved.
I used store.subscribe to solve it this way:
<template>
<div class="google-map" :id="mapName"></div>
</template>
<script>
import GoogleMapsLoader from 'google-maps';
import { mapGetters } from 'vuex';
export default {
name: 'google-map',
props: ['name'],
computed: {
...mapGetters({
locations: 'locations/locations',
}),
},
data() {
return {
mapName: `${this.name}-map`,
};
},
mounted() {
this.$store.subscribe((mutation, state) => {
if (mutation.type === 'locations/SAVE_LOCATIONS') {
GoogleMapsLoader.KEY = 'myKey';
GoogleMapsLoader.load((google) => {
/* eslint-disable no-new */
const map = new google.maps.Map(document.getElementById('locations-map'));
// loop through locations and add markers to map and set map boundaries
const bounds = new google.maps.LatLngBounds();
// I access the resulting locations array via state.module.property
state.locations.locations.forEach((location) => {
new google.maps.Marker({
position: {
lat: location.latitude,
lng: location.longitude,
},
map,
});
bounds.extend({
lat: location.latitude,
lng: location.longitude,
});
});
map.fitBounds(bounds);
});
}
});
},
};