Call an another API in async await return statement not working - async-await

I want to call another Axios request after one. But as in the code console. log('skip..) prints first and then my other Axios request runs, But I need to wait for the post-request result and then return the value. If I add await before power bi Axios post request I got an error. Can anyone suggest what to do here?
enter image description here
async getDashboards({commit}, id){
return await axios.get(`${url}/groups/${group_id}/reports/${id}`)
.then((resp)=>{
if(resp.data){
axios.post('https://api', {
"datasets": [{'id' : resp.data.datasetId}],
"reports": [{'id' : id}],
"targetWorkspaces": [{'id' : resp.data.datasetWorkspaceId }],
})
.then((dataResp)=>{
console.log('dataResp')
localStorage.setItem('embedded_token', dataResp.data.token)
localStorage.setItem('embedded_token_expiry_time', dataResp.data.expiration)
localStorage.setItem('embedded_token_ID', dataResp.data.tokenId)
})
.catch((error)=>{
if(error){
return false
}
})
console.log('skip...')
commit('addDashboard', resp.data)
return resp.data
}
return false
})
.catch(() => false)
}

Related

Cypress cy.request .then chaining returning undefined

I'm upgrading Cypress from 10.2.0 to 10.11.0 and I'm encountering some behaviour I'm trying to understand.
In the second .then, the response is undefined. This had previously worked on 10.2.0.
public makeRequest(params) {
return cy.request({
...params
})
.then((response) => {
// do something with response
});
}
this.makeRequest(params)
.then((response) => {
// response is undefined
});
Can anyone point me in the right direction, I have checked the changelogs for every version since 10.3.0 and cannot find anything to explain this behaviour.
Thanks!
Cypress (version 10.11.0 and previous versions) returns the last command result taken within the cy.request().then() chain, when there is no explicit return value given.
For example, if // do some async tasks is a non-Cypress asynchronous query, the response is returned:
cy.visit('http://example.com');
function makeRequest(params) {
return cy.request(params)
.then((response) => {
// do some async tasks
setTimeout(() => {
console.log(response.title)
expect(response.body.title).to.eq('delectus aut autem') // passes
}, 1000)
})
}
makeRequest({url: 'https://jsonplaceholder.typicode.com/todos/1'})
.then(response => {
expect(response.body.title).to.eq('delectus aut autem') // passes
})
If however you issue more Cypress commands inside the // do some async tasks block, the last chained "subject" changes, and you get a different return value
cy.visit('http://example.com');
function makeRequest(params) {
return cy.request(params)
.then((response) => {
// do some async tasks
cy.get('h1') // changes "subject" from response to <h1> element
})
}
makeRequest({url: 'https://jsonplaceholder.typicode.com/todos/1'})
.then(response => {
console.log(response) // not your response, but the last "subject" found above
expect(response.text()).to.eq('Example Domain') // passes
})
Adding a return returns the response
public makeRequest(params) {
return cy.request({
...params
})
.then((response) => {
// do something with response
return response;
});
}
If you are doing some async tasks in makeRequest.then(), do your async tasks and return response in another .then. E.g:
public makeRequest(params) {
return cy.request({
...params
})
.then((response) => {
// do some async tasks
})
.then((response) => {
return response;
});
}

error Policy in Apollo Client React does'nt work

I have aproblem when test Apollo.When I try query with apollo and graphql, i want response return error and partical data, so I set property errorPolicy:'all'. But its not work. I don't no why? Help please!
Here my code:
query { animal {
name
age }, school {
name
numberfd } } `
const { loading,data,error} = useQuery(GET_DASHBOARD_DATA, {
errorPolicy:'all',
onCompleted: (res) => {console.log("complete",res)},
onError : (res,data) => {console.log("ERRRR",res,data)},
})
and i want to receive:
{
error:[...], data:[animal:[...]] }
but its only response error.Here is Apollo's doc: https://www.apollographql.com/docs/react/data/error-handling/
onError type is onError?: (error: ApolloError) => void;. You don't have data inside onError callback.
After useQuery you can add:
console.log('data', data)
console.log('error', error)
I faced the same issue with errorPolicy: 'all', I only received the partial result inside onCompleted callback of useQuery, but no errors.
I created an ErrorLink like this:
private createErrorLink = () => {
return new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
// filter out errors you don't want to display
const errors = filterSomeErrors(response.errors);
if (errors && response?.data) {
response.data.errors = errors;
}
return response;
});
});
};
Now inside my onCompleted callback I get my data as well as errors. You will have to tweak your types a bit, because seems there is no errors field on response.data by default.
Mind that if you use onError from Apollo and return something from the link, it will retry your request containing errors!

asyncData not being called on refresh in a nested route

I have a blog detail page, which has a asyncData call to t he blog ID requested. When the redirection happens from index to the detail page, the asyncData requests the detail, but when I refresh the detail page there is no call made. The first code is from index.vue and the the second is the nested component.
async asyncData() {
const { data } = await axios.get(
'https://calltocms.com/_/items/blog?meta=total_count%2Cresult_count&limit=50&offset=0&fields=%2A.%2A.%2A&sort=-publishing_date'
)
return { articles: data }
}
asyncData({ params, error }) {
return axios
.get(
`https://calltocms.com/_/items/blog/${+params.id}?fields=%2A.%2A.%2A`
)
.then(res => {
return { post: res.data }
})
.catch(e => {
error({ statusCode: 404, message: 'Post not found' })
})
}
I want the asyncData call to be made on refresh from the nested component.

Nuxt.js and Laravel Api - 422 Displaying Error instead of Forms

[Error][1]
Hi Team,
Whenever I am receiving the error return from laravel the nuxt.js project displays the error on the page instead the HTML/Forms. How can i handle this.
Here is my php code
return response()->json([
'errors' => [
'email' => ['Sorry we cant find you with those details.'],
],
], 422);
Javascript
async submit() {
await this.$auth.loginWith("local", {
data: this.form
})
In your JavaScript you need to wrap your await promise inside a try catch block. Here's a fix for your JS.
try {
await this.$auth.loginWith("local", {
data: this.form
})
} catch (e) {
return;
}
This is an old question at this point, but I thought I'd post the full code since I was pretty stumped and didn't find many great answers out there:
async handleSubmit() {
try {
const authResponse = await this.$auth.loginWith('local', {
data: this.formData
});
const { status, data } = authResponse;
if (status === 200)
this.createFlashAlert({ 'success': 'Login successful' });
} catch (error) {
if (error.response.status === 422)
this.createFlashAlert(error.response.data);
}
}
So the checklist:
Wrap the login call in a try/catch if you're using async await syntax (be sure to make it an async function i.e. async handleSubmit.
in the catch block, use the error.response object, this is an axios thing. With this you'll be able to access the response status and data.
If you log just the error object, it's not obvious that you can access the response within that error which is what had me stumped.

Return axios Promise through Vuex

all!
I need to get axios Promise reject in my vue component using vuex.
I have serviceApi.js file:
export default {
postAddService(service) {
return axios.post('api/services', service);
}
}
my action in vuex:
actions: {
addService(state, service) {
state.commit('setServiceLoadStatus', 1);
ServicesAPI.postAddService(service)
.then( ({data}) => {
state.commit('setServiceLoadStatus', 2);
})
.catch(({response}) => {
state.commit('setServiceLoadStatus', 2);
console.log(response.data.message);
return Promise.reject(response); // <= can't catch this one
});
}
}
and in my vue component:
methods: {
addService() {
this.$store.dispatch('addService', this.service)
.then(() => {
this.forceLeave = true;
this.$router.push({name: 'services'});
this.$store.dispatch('snackbar/fire', {
text: 'New Service has been added',
color: 'success'
}).then()
})
.catch((err) => { // <== This never hapens
this.$store.dispatch('snackbar/fire', {
text: err.response.data.message || err.response.data.error,
color: 'error'
}).then();
});
}
When i use axios directly in my component all work well. I get both success and error messages.
But when i work using vuex i can't get error message in component, hoever in vuex action console.log prints what i need.
I'm always getting only successfull messages, even when bad things hapen on beckend.
How can i handle this situation using vuex ?
Wellcome to stackoverflow. One should not want to expect anything back from an action. After calling an action. Any response should be set/saved in the state via mutations. So rather have an error property on your state. Something like this should work
actions: {
async addService(state, service) {
try {
state.commit('setServiceLoadStatus', 1);
const result = await ServicesAPI.postAddService(service);
state.commit('setServiceLoadStatus', 2);
} catch (error) {
state.commit("error", "Could not add service");
state.commit('setServiceLoadStatus', 2);
console.log(response.data.message);
}
}
}
And in your component you can just have an alert that listens on your state.error
Edit: Only time you are going expect something back from an action is if you want to call other actions synchronously using async /await. In that case the result would be a Promise.

Resources