4👍
Personally I feel sending the data back to the component is not the ideal way. Instead, you can have another constant (like below) in actions.js and have a getter for the same. Access the getter in your component as a computed property.
// actions.js
const state = {
api: {
fetch: {
inProgress: false,
completed: false,
success: false,
error: false,
},
data: {}
}
}
const getter = {
'API_DATA': state => {
return state.api
}
}
const mutations = {
'SET_API_DATA_FETCH_IN_PROGRESS': state => {
state.api.fetch.inProgress = true
state.api.fetch.completed = false
state.api.fetch.success = false
state.api.fetch.error = false
state.api.data = {}
},
'SET_API_DATA_FETCH_SUCCESS': (state, payload) => {
state.api.fetch.inProgress = false
state.api.fetch.completed = true
state.api.fetch.success = true
state.api.fetch.error = false
state.api.data = payload
},
'SET_API_DATA_FETCH_ERROR': (state, payload) => {
state.api.fetch.inProgress = false
state.api.fetch.completed = true
state.api.fetch.success = false
state.api.fetch.error = true
state.api.data = payload
}
}
const contactAuthor = ({ commit }, payload) => {
commit('SET_API_DATA_FETCH_IN_PROGRESS')
API.post('send-message', payload).then((response) => {
if (response.status === 200 && response.data.success) {
// WHAT TO RETURN HERE TO SET SUCCESS TO TRUE IN COMPONENT?
commit('SET_API_DATA_FETCH_SUCCESS', response)
} else {
commit('SET_API_DATA_FETCH_ERROR', response)
console.log('Something went wrong');
}
}).catch((error) => {
commit('SET_API_DATA_FETCH_ERROR', response)
console.log('Something went wrong');
});
}
// component.vue
computed: {
apiDataFetchSuccess() {
return this.$store.getters.API_DATA.fetch.success
},
apiData() {
return this.$store.getters.API_DATA.data
}
}
1👍
Okay so this worked.
const contactAuthor = (payload) => {
return API.post('send-message', payload).then((response) => {
if(response.status === 200 && response.data.success) {
const trueMessage = true;
return trueMessage;
} else {
console.log('Something went wrong');
}
}).catch((error) => {
console.log('Something went wrong');
});
}
returning promise from axios and then returning trueMessage
from contactAuthor
and then setting it up like this in component:
this.$store.dispatch('contactAuthor', message).then(data => {
this.success = data;
});
0👍
In your store mutations, you have to do something like this:
return new Promise((resolve, reject) => {
API.post('send-message', payload).then((response) => {
if(response.status === 200 && response.data.success) {
const trueMessage = true;
resolve(trueMessage)
} else {
reject('Something went wrong')
console.log('Something went wrong');
}
}).catch((error) => {
reject(error)
console.log('Something went wrong');
});
})
In your component do something like this:
this.$store.dispatch('contactAuthor', message)
.then( (success) => {
//OK, do something
})
.catch( (error) => {
// ERROR, do something
});
Source:stackexchange.com