My Vue.js code about Axios and function is not working - javascript

I want to execute function2 after axios. I got no catch error. but still Function2 is not executed.
The code i want but not working :
add: function () {
axios.post('/add', this.person)
.then(response => {
if (response.data.etat) {
this.person = {};
this.function2();
}
})
.catch(error => {
console.log('errors: ', error)
})},
This is working, but i would like to execute function2 only if axios pass.
add: function () {
axios.post('/add', this.person)
.then(response => {
if (response.data.etat) {
this.person = {};
}
})
.catch(error => {
console.log('errors: ', error)
})
this.function2();
},
Any help ? thank you !

You can chain .then() blocks:
add: function () {
axios.post('/add', this.person)
.then(response => {
if (response.data.etat) {
this.person = {};
}
})
.then(() => {
this.function2();
})
.catch(error => {
console.log('errors: ', error)
})
}
this.function2 will be called only if your axios.post is successful and if the first .then() doesn't throw any error. In another case - your .catch() will catch the error.
Here you can see how it works on live:
https://codepen.io/anon/pen/gZQyym?editors=1111

Since you're using axios to post data, and you want to do call that method after the operation is done successfully so you should check the response status like :
add: function () {
axios.post('/add', this.person)
.then(response => {
if (response.status==200) {
this.person = {};
this.function2();
}
})
.catch(error => {
console.log('errors: ', error)
})},

Related

Function returning undefined

I have a function that calls an API and returns some data:
async function getDataAxios(){
await axios.get("http://localhost:8080/cards/1").then(response => {
console.log("RESP: ", response.data[0])
return response
})
.catch(err => {
console.log("Error: ", err)
return err
})
}
When I log response.data[0] inside getDataAxios() the expected data is present.
But when I try and return the data to my calling function and log the return data it logs undefined:
getDataAxios().then(r => console.log(r))
I have also tried the following:
const resp = getDataAxios().then(resp => console.log("Data 2: ", resp)).catch(
err => {
console.log("An error has occurred: ", err)
return err;
}
)
console.log(resp)
Full code:
function App() {
getDataAxios().then(r => console.log(r))
}
async function getDataAxios(){
await axios.get("http://localhost:8080/cards/1").then(response => {
console.log("RESP: ", response.data[0])
return response
})
.catch(err => {
console.log("Error: ", err)
return err
})
}
export default App;
Just adding here some more details, since the comment was not very detailed.
You have
async function getDataAxios(){
await axios.get(...).then(...).catch(...);
}
and
function App() {
getDataAxios().then(r => console.log(r))
}
The getDataAxios method does not return anything. The then inside it does return a value, but that is not returned from the actual getDataAxios function.
Nothing wrong with that on its own, if the then code is all you wanted to perform.
But you then call it in the App and use then on it, getDataAxios().then(r => console.log(r)). The r here will contain whatever was returned from the getDataAxios which is nothing, so the r will be undefined.
Adding the return to the getDataAxios will return the promise. And since the return value type of axios is a promise you do not have to specify async, nor await for it.
So you can use
function getDataAxios(){
return axios.get(...).then(...).catch(...);
}
and now you can use it as you already do, as
function App() {
getDataAxios().then(r => console.log(r))
}
Turn the response into a constant and than store data in it and than return it. Do this instead.
async function getDataAxios(){
await axios.get("http://localhost:8080/cards/1").then(response => {
console.log("RESP: ", response.data[0])
const response = response.data[0]
return response
})
.catch(err => {
console.log("Error: ", err)
return err
})
}
Or you can do this
async function getDataAxios(){
await axios.get("http://localhost:8080/cards/1").then(response => {
console.log("RESP: ", response.data[0])
return response.data[0]
})
.catch(err => {
console.log("Error: ", err)
return err
})
}

Exsport function with Api call then import it on another page and wait for data

I'm new to all this export, import, async so please bare with me.
I have one file where I make API call and export that function so it can be used across other pages.
Of course on other page when function is invoked data payload is not yet there so i get undefind. So i tried to implement async (first time).
Please correct me if this is even possible or I I need some other method.
app.js:
export function inboxMeniIkona () {
//let req = xxxx
fetch(req)
.then(response => {
if (response.ok) {
return response.json()
} else {
throw new Error('NETWORK RESPONSE ERROR')
}
})
.then(data => {
return new Promise(resolve => {
return data // data here is allright
});
})
.catch(error => console.error('FETCH ERROR:', error))
}
And then I tried on other page:
import { inboxMeniIkona } from '~/app'
async function asyncCall() {
console.log('calling');
const result = await inboxMeniIkona();
console.log(result);
// expected output: "resolved"
}
asyncCall();
I'm still getting
CONSOLE LOG: calling
CONSOLE LOG: undefined
Please advise
Add async in your functions and await in your fecth and return it like this.
export async function inboxMeniIkona () {
//let req = xxxx
return await fetch(req)
.then(response => {
if (response.ok) {
return response.json()
} else {
throw new Error('NETWORK RESPONSE ERROR')
}
})
.then(data => {
return data // data here is allright
})
.catch(error => console.error('FETCH ERROR:', error))
}

Axios prints value on console but returns undefined

I have quite an issue for some time and is getting on my nerves and it doesn't make sense. I have used axios on my react frontend and it works perfect when assigning the get value to the state. But when using it in a normal javascript code, I appear to have this following issue: i can print the object's value in the console but it will return only undefined.. Here is my code:
login = () => {
let data;
axios.get('https://myaddress/authenticate')
.then(response => {
data = response;
console.log('data here', data);
})
.catch(error => {
console.error('auth.error', error);
});
console.log('eee', data);
return data;
};
Here we are talking about axios strictly.
You can't return an ajax response because it's asynchronous. You should wrap your function into a promise or pass a callback to login
UPDATE: As #Thilo said in the comments, async/await would be another option, but it will let you set the response to data tho ...
1. Wrap into a promise
login = () => new Promise((resolve, reject)=>{
axios.get('https://myaddress/authenticate')
.then(response => {
resolve(response)
})
.catch(error => {
reject(error)
});
});
// Usage example
login()
.then(response =>{
console.log(response)
})
.catch(error => {
console.log(error)
})
2. Pass a callback
login = (callback) => {
axios.get('https://myaddress/authenticate')
.then(response => {
callback(null,response)
})
.catch(error => {
callback(error,null)
});
};
// Usage example
login((err, response)=>{
if( err ){
throw err;
}
console.log(response);
})
3. Async/Await
login = async () => {
// You can use 'await' only in a function marked with 'async'
// You can set the response as value to 'data' by waiting for the promise to get resolved
let data = await axios.get('https://myaddress/authenticate');
// now you can use a "synchronous" data, only in the 'login' function ...
console.log('eee', data);
return data; // don't let this trick you, it's not the data value, it's a promise
};
// Outside usage
console.log( login() ); // this is pending promise
In ES7/ES8 you can do async/await like a boss:
login = () => {
return new Promise((resolve, reject) => {
axios.get('https://myaddress/authenticate')
.then(response => {
resolve(response)
})
.catch(error => {
console.error('auth.error', error);
reject(error)
});
});
};
async function getData() {
try{
const data = await login()
} catch(error){
// handle error
}
return data;
}
getData()
.then((data) => console.log(data));

Why is this promise not resolving back to the caller?

I have a Vue-App which runs with Vuex and Axios. In this app I have vuex-store which handles API-calls, but a problem is that when I call the store-actions I cant chain the response in the caller.Any ideas what Im doing wrong?
Calling code:
import { FETCH_PRODUCTS, ADD_PRODUCT } from './actions.type'
methods: {
sendNewProduct () {
this.$store
.dispatch(ADD_PRODUCT, this.newProductForm)
.then(() => {
console.log('This never gets called')
})
}
}
Vuex-store:
const actions = {
[ADD_PRODUCT] (context, credentials) {
return new Promise((resolve) => {
ApiService
.post('/Products/', {
Name: credentials.Name,
Description: credentials.Description,
Price: credentials.Price
})
.then(({ data }) => {
this.$store
.dispatch(FETCH_PRODUCTS)
resolve(data)
})
.catch(({ response }) => {
console.log(response)
context.commit(SET_ERROR, 'Error adding product')
})
})
}
}
const actions = {
[ADD_PRODUCT](context, credentials) {
return ApiService.post("/Products/", {
Name: credentials.Name,
Description: credentials.Description,
Price: credentials.Price
})
.then(({ data }) => {
this.$store.dispatch(FETCH_PRODUCTS);
return data;
})
.catch(({ response }) => {
console.log(response);
context.commit(SET_ERROR, "Error adding product");
throw new Error("Error adding product");
});
}
};
I've removed the new Promise(...) because axios already creates a promise.
If added a return data in the then callback and a throw in the catch callback to let the calling api receive the data/error.
Note that the promise resolves before the FETCH_PRODUCTS completes, to make sure that action is also completed, you'd write:
.then(({ data }) => {
return this.$store.dispatch(FETCH_PRODUCTS)
.then(() => data);
})

TypeScript/RxJS - Observable subscribe() method complete() not running

I've had a good look around to try and solve this but can't find an answer that works.
I'm trying to implement a callback for an additional function when a subscribe() method successfully returns an 'contacts$' observable, but using complete() on the subscription does not do anything.
I've also tried using finally() on the observable as suggested elsewhere, but this also doesn't work.
Using complete():
ngOnInit() {
this.getContacts().subscribe(
data => {
this.contacts = data;
console.log('NewInvoice.contacts:', data);
this.selectedContactId = this.contacts[0].id;
console.log('selectedContactId: ' + this.selectedContactId);
},
error => {
console.error('Error getting contacts via subscribe() method:', error);
},
() => {
this.getSelectedContact();
}
)
}
Using finally():
ngOnInit() {
this.getContacts()
.finally(() => console.log('a'))
.subscribe(
data => {
this.contacts = data;
console.log('NewInvoice.contacts:', data);
this.selectedContactId = this.contacts[0].id;
console.log('selectedContactId: ' + this.selectedContactId);
},
error => {
console.error('Error getting contacts via subscribe() method:', error);
},
() => {
this.getSelectedContact();
}
)
}
Method for callback on observable completion:
getSelectedContact() {
this.contactsCollection.doc(this.selectedContactId).ref.get().then(snapshot => {
this.selectedContact = snapshot.data() as Contact;
console.log('selectedContact:', this.selectedContact);
})
}
Difficult to say without more info, but I'll give a shot:
ngOnInit() {
this.getContacts()
.subscribe(
data => {
this.contacts = data;
console.log('NewInvoice.contacts:', data);
this.selectedContactId = this.contacts[0].id;
console.log('selectedContactId: ' + this.selectedContactId);
},
error => {
console.error('Error getting contacts via subscribe() method:', error);
},
() => {
this.getSelectedContact()
.asObservable()
.subscribe((a) => console.log(a));
}
)
}
And :
getSelectedContact() {
return this.contactsCollection.doc(this.selectedContactId).ref.get().then(snapshot => {
this.selectedContact = snapshot.data() as Contact;
console.log('selectedContact:', this.selectedContact);
})
}
Or a little cleaner :
const callback = (a) => console.log(a);
...
() => {
this.getSelectedContact(callback);
}
...
getSelectedContact(callback) {
this.contactsCollection.doc(this.selectedContactId).ref.get()
.then(snapshot => {
this.selectedContact = snapshot.data() as Contact;
console.log('selectedContact:', this.selectedContact);
})
.then(a => callback(a));
}
Lastly as #Picci suggested :
this.getContacts()
.last()
.exhaustMap((data) => this.getSelectedContact(data))
.map(a => console.log(a))
.subscribe();
Beware that all the above code is absoultely not tested and only for reference.

Categories