I have a component file in which I send id using dispatch:
mounted() {
const warehouseId = this.$route.params.id;
this.$store.dispatch("showWarehouse", {warehouseId}).then(() => {
this.warehouseData = this.$store.state.showWarehouses;
});
},
I get id of element from route (warehouseId), next I run action showWarehouse.
In store.js (Vuex) file I have an action:
showWarehouse({ commit }, payload) {
return new Promise((resolve, reject) => {
axios.get('/api/warehouse/' + payload)
.then(response => {
commit('showWarehouse', response.data);
resolve();
})
.catch(error => {
console.warn(error);
});
});
}
I try get id from componnt using payload, but probably this value is undefined. When I change:
axios.get('/api/warehouse/' + payload)
to
axios.get('/api/warehouse/1')
axios return correctly data from database.
Ok, I found a solution
I must just add payload.warehouseId:
axios.get('/api/warehouse/' + payload.warehouseId)
warehouseId must been this the same name from a component:
this.$store.dispatch("showWarehouse", {warehouseId})
Related
i already call the axios and show using console log if it is successful or not already, However i wanted to pass the axios post response value to my vue component and display the response in my vue component in order for me to make a condition. Is there any way to do it? I try some other part but no luck. Kindly guide me.
main.vue
methods: {
onClicked() {
this.$store
.dispatch('Clickme', this.data)
.then(() => {
alert("Success");
})
.catch(() => {
alert("Error");
})
}
}
clicked.js
return new Promise((resolve, reject) => {
clicked(username, password)
.then(resp => {
console.log("---->>>> : ");
const data = resp.data.data
console.log(username, password);
console.log(resp);
console.log("statresponse.status : " + resp.data.status);
console.log("statresponse.message : " + resp.data.message);
console.log("statresponse.inside message : " + resp.data.data.message);
// console.log("USER.JS RESPONSE: " + resp.data.status);
// console.log("USER.JS RESPONSE: " + resp.data.message);
setToken(data.token)
commit('SET_TOKEN', data.token)
resolve()
})
.catch(error => {
console.log(error)
reject(error)
})
})
Try changing main.vue to:
onClicked() {
this.$store
.dispatch('Clickme', this.data)
.then((response) => {
//Do whatever you want with your response
alert("Success");
})
.catch(() => {
alert("Error");
})
}
and change clicked.js to:
resolve(resp.data.data)
This will make so the promise resolves the response data.
However if you make the http request in your store/using vuex, what you probably want to do is commit a mutation to put the response into your state - and then map the state from your component.
Redux store get undefined in action.data, even though my reducer function gets the correct result from the api, my dispatch is in the correct place.
My Reducer function:
const convertPosition = StateHelper.createAsyncOperation(MODULE, 'convertPosition');
export function $convertPosition(lat, long) {
return (dispatch) => {
dispatch(Activity.$processing(MODULE, $convertPosition.name));
dispatch(convertPosition.request());
return fetch(`${API_ENDPOINT}/shared/maps/address?latlong=${lat},${long}`, {
headers: {
Authorization: `Bearer ${AuthService.getAccessToken()}`,
},
})
.then(FetchHelper.ResponseHandler, FetchHelper.ErrorHandler)
.then((result) => dispatch(convertPosition.success(result)))
.catch((error) => dispatch(convertPosition.failure(error)))
.finally(() => dispatch(Activity.$done(MODULE, $convertPosition.name)));
};
}
My Reducer statement:
case convertPosition.SUCCESS:
return {
...state,
locationName: action.data,
};
case convertPosition.FAILURE:
return {
...state,
locationName: null,
};
After I checked the API with postman, the result was an array so the code was:
...
.then((result) => dispatch(convertPosition.success({result: result})))
....
I'm trying to find the correct way to get the number of returned results from my async axios get query but not getting anywhere so hoping someone can assist
My code is as follows
mounted() {
axios.get('http')
.then(response => {
this.myItems = response.data // this works
countResults(response) //this doesn't seem to
.catch(error => console.log(error))
})
},
filters:{
countResults: function(value){
return value.length;
}
I then call as follows
<p>Number of Entries: {{countResults}}</p>
Thanks
You can call the filter method in this way
this.$options.filters.countResults(response)
To solve your problem you need to store the response. You can do that in this way
mounted() {
axios.get('http')
.then(response => {
this.myItems = response.data // this works
this.responseData = response.data
}).catch(error => console.log(error))
},
data: {
responseData: []
},
filters: {
countResults: function(){
return this.responseData.length;
}
How to catch axios exceptions in vuex store and throw it to vue.js method ? My goal is to get this exception to be able to reset computed values bound to input using this.$forceUpdate().
In my method, I have this:
methods: {
mymet: _.debounce(
function(table, id, key, event) {
const value = event.target.value;
this.$store.dispatch('UPDATE_TRANSACTIONS_ITEM', { table, id, key, value }).then(response => {
event.target.classList.remove("is-invalid")
event.target.classList.add("is-valid")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again")
this.$forceUpdate();
})
}, 500
)
}
In my vuex store, I have this:
const actions = {
UPDATE_TRANSACTIONS_ITEM ({ commit }, data) {
let company = {
[data.key]: data.value
}
axios.put(`/api/companies/${data.id}`, { company }).then( function ( response ) {
commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data })
}).catch(function (error) {
throw error
})
}
}
const mutations = {
SET_TRANSACTIONS_ITEM_UPDATE (state, { profile }) {
state.company_data[profile.key] = profile.value
},
}
You need to make the actual action function asynchronous.
If you have the ability to use async functions, you can just await the axios call, and let the error bubble up (no need to throw anything in the action itself):
const actions = {
async UPDATE_TRANSACTIONS_ITEM ({ commit }, data) {
let company = {[data.key]: data.value};
await axios.put(`/api/companies/${data.id}`, { company }).then(() => {
commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data })
});
}
}
Otherwise, you'll need to return a Promise and catch the error and pass it to the reject handler:
const actions = {
UPDATE_TRANSACTIONS_ITEM ({ commit }, data) {
return new Promise((resolve, reject) => {
let company = {[data.key]: data.value};
axios.put(`/api/companies/${data.id}`, { company }).then(() => {
commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data });
resolve();
}, (error) => reject(error));
});
}
}
I am wondering how to use async/await actions in Vuex. The docs provide this syntax as an example:
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // wait for `actionA` to finish
commit('gotOtherData', await getOtherData())
}
}
Following this example, I have:
import Vue from 'vue';
import Vuex from 'vuex';
import * as firebase from 'firebase';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
// other state vars here
resource: null
},
mutations: {
// saveValues
setResource(state, payload) {
state.resource = payload;
}
},
actions: {
async getResource({ commit, dispatch }) {
var resource
console.log('resource1: ' + resource)
Vue.http.get('https://mysite/api/getResource')
.then((response) => {
console.log('get resource')
var data = response.body;
resource = data.access_resource;
console.log('resource2: '+ resource)
commit('setResource', resource);
var foo = store.getters.resource;
console.log('resource3: ' + foo);
}, (error) => {
console.log(error);
});
},
async getSomeApi({ commit, dispatch }) {
console.log('getting api');
await dispatch('getResource');
var resource = store.getters.resource;
console.log('resource4: ' + resource);
Vue.http.get('https://somesite/api/someapi?resource=' + resource)
.then((response) => {
console.log("got something from somesite")
var data = response.body;
// do something with data -> payload
dispatch('saveValues', payload);
}, (error) => {
console.log(error);
});
}
},
getters: {
resource(state) {
return state.resource;
}
}
});
However, even following the syntax example found in the docs, when I run this code, the async/await seem to be completely ignored. When I look at the logs, I see, in the following order:
getting api
resource1: undefined
resource4: null
get resource
resource2: <expected-value>
resource3: <expected-value>
I expect the console.log statements to print out in numerical order. I would appreciate if someone could clarify what I am doing wrong.
You're not awaiting the Vue.http.get() promise in the getResource() method, so await dispatch('getResource') will resolve before the HTTP request has resolved.
Trimmed down:
async getResource() {
let response
try {
response = await Vue.http.get('https://mysite/api/getResource')
} catch (ex) {
// Handle error
return
}
// Handle success
const data = response.body
}