call multiple async functions in sequential order - javascript

async function unsubscribeUserHandler() {
const unsubscribe = await fetch("/api/stripe-sessions/cancel-subscription", {
method: "PATCH",
body: JSON.stringify(),
headers: {
"Content-Type": "application/json",
},
});
const data = await unsubscribe.json();
if (!unsubscribe.ok) {
Toast.fire({
icon: "error",
title: `${data.message}`,
});
} else {
Toast.fire({
icon: "success",
title: `${data.message}`,
});
}
}
async function deleteUserHandler() {
const deleteUser = await fetch("/api/user/delete-account", {
method: "DELETE",
body: JSON.stringify(),
headers: {
"Content-Type": "application/json",
},
});
const data = await deleteUser.json();
if (!deleteUser.ok) {
Toast.fire({
icon: "error",
title: `${data.message}`,
});
} else {
Toast.fire({
icon: "success",
title: `${data.message}`,
});
}
}
const deleteAccount = async () => {
try {
await unsubscribeUserHandler();
await deleteUserHandler();
} catch (err) {
console.error('ERROR#####!!!',err);
}
}
const Settings = () => {
return <DeleteAccount onDeleteAccount={deleteAccount} />;
};
As shown here, I want to unsubscribe.. only after the unsub, then run delete handler.
I have issues where It only runs one of the handlers and not the other. Are there other ways to do this?
have tried:
.then(() => deleteUserHandler())
and
.then(deleteUserHandler)
above doesn't make call to /api/user/delete-account,
only to unsubscribe.

This is wrong:
const deleteAccount = () => unsubscribeUserHandler()
.then(deleteUserHandler())
.catch(console.error);
You aren't passing deleteUserhandler to then(), you are immediately calling it and pass the result to then().
To fix, lose the parenthesis:
const deleteAccount = () => unsubscribeUserHandler()
.then(deleteUserHandler)
.catch(console.error);
Or use an arrow function:
const deleteAccount = () => unsubscribeUserHandler()
.then(() => deleteUserHandler())
.catch(console.error);
Or better yet:
const deleteAccount = async () => {
try {
await unsubscribeUserHandler();
await deleteUserHandler();
} catch (err) {
console.error(err);
}
}

Related

React Native - Why isn't the function getting called?

I have a function inside another function that won't get called.
First function:
const getToken = dispatch => async () => {
try {
GoogleSignin.configure({
webClientId: 'XXXX',
iosClientId: 'XXXX',
});
const {idToken} = await GoogleSignin.signIn();
const googleCredential =
firebase.auth.GoogleAuthProvider.credential(idToken);
const userCredential = await firebase
.auth()
.signInWithCredential(googleCredential);
const token = userCredential.user.uid;
secondFunction(token);
} catch (err) {
dispatch({
type: 'error_1',
payload: 'error',
});
}
};
2nd function:
const secondFunction = dispatch => token => {
console.log('second function called');
try {
axios.post(url, token).then(res => {
console.log(res.data);
const response = res.data;
} catch (err) {
dispatch({
type: 'error_1',
payload: 'error',
});
}
};
might be something simple I'm not getting. Would appreciate any help!
Should be
secondFunction(dispatch)(token)
Because your console.log was inside nested function

My first api request always fails after page load

I'm having a problem with my API request that always fails after page load. Don't really know where Im wrong.
Here's my request and I call it when I interact with handleOpen function.
const stock = {
method: 'GET',
url: 'https://morningstar1.p.rapidapi.com/live-stocks/GetRawRealtimeFigures',
params: {Mic: props.mic, Ticker: clickedElement.ticker},
headers: {
'x-rapidapi-key': 'XXX',
'x-rapidapi-host': 'morningstar1.p.rapidapi.com'
}
}
const getStock = async () => {
try {
const res = await axios.request(stock);
return res.data;
}
catch (error) {
setOpen(false);
console.error("catch api error: ", error);
}
}
const handleOpen = name => {
let findClickedStock = props.stocksArray.find(item => item.ticker === name)
setClickedElement(findClickedStock)
getStock().then((dataFromStockApi) => {
let combined1 = { ...dataFromStockApi, ...findClickedStock }
setStockObject(combined1);
});
setOpen(true);
};
ERROR:
It's because your Ticker parameter is empty.
When you create "stock", clickedElement.ticker is undefined.
Do this:
// pass name in as a parameter
getStock(name).then(...)
Make getStock like like this:
const getStock = async (ticker) => {
try {
const res = await axios.request({
method: 'GET',
url: 'https://morningstar1.p.rapidapi.com/live-stocks/GetRawRealtimeFigures',
params: {Mic: props.mic, Ticker: ticker},
headers: {
'x-rapidapi-key': 'XXX',
'x-rapidapi-host': 'morningstar1.p.rapidapi.com'
}
});
return res.data;
}
catch (error) {
setOpen(false);
console.error("catch api error: ", error);
}
}

Testing functions calls inside callback with jest - React-native -

I'm testing the behavior of a function with a success api call, i managed to mock the fetch response, but the function inside then callback are not called, even if console.log showing the function is going inside the callback.
My test is failing here:
Here is the function im testing:
tryUserLogin() {
this.setState({loading: true});
const randomPassword = Math.random()
.toString(36)
.slice(-8);
const email = this.state.inputEmail;
const name = this.state.inputName;
const formData = new FormData();
formData.append('email', email);
formData.append('name', name);
formData.append('password', randomPassword);
const query = Util.urlForAddUser();
fetch(query, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
if (responseJson.code === 200) {
firebase.analytics().logEvent('userSuccessfulLogIn', {
userId: responseJson.response.id,
});
const userData = responseJson.response;
console.log('userData',userData) // <==== i can see this in console
this.storeUserData(userData, name);
this.setState({loading: false});
this.handleModalVisibility();
this.props.handelAddComment();
console.log('finish')
} else {
Alert.alert(
this.props.t('common:title_error'),
this.props.t('common:error'),
);
this.setState({loading: false});
}
})
.catch(error => {
firebase.crashlytics().log(
`error tryUserLogin
LoginModal===>> ${error.message}`,
);
Alert.alert(
this.props.t('common:title_error'),
this.props.t('common:error'),
);
this.setState({loading: false});
});
}
And here is the test:
it('testing tryUserLogin code 200 case', async () => {
global.FormData = require('FormData');
global.fetch = jest.fn();
const userData = {
code: 200,
response: {
id: 1,
email: 'test+1234567890#t.com',
},
};
const name = 'test';
const email = 'test#t.com';
const spyStoreUserData = jest.spyOn(instance, 'storeUserData');
const spyHandelModalVisibility = jest.spyOn(
instance,
'handleModalVisibility',
);
fetch.mockImplementation(() => {
return Promise.resolve({
status: 200,
json: () => {
return Promise.resolve({
...userData,
});
},
});
});
instance.setState({inputName: name});
instance.setState({inputEmail: email});
await instance.tryUserLogin();
expect(spyStoreUserData).toBeCalledWith(userData.response, name);
expect(fetch.mock.calls[0][0]).toBe('testQuery');
expect(instance.state.loading).toBe(false);
expect(spyHandelModalVisibility).toBeCalled();
expect(mockHandelAddComment).toBeCalled();
});

nested axios call with await in vue js

i am new to async and i have an action in vuex that get user's info and i put that in promise and i want to use this method in then block of axios call for login with await because data of user info is important for me
my problem is i cant use await in then block and error says the error says await can only be use in async function
this flow is correct and what is correct way?
store.js:
actions: {
loadUserInfo({commit}){
const headers = {
'Content-Type': 'application/json',
// 'Authorization': localStorage.getItem('access_token'),
'Accept': 'application/json'
}
return new Promise(function(resolve, reject) {
axios.get(process.env.VUE_APP_BASE_URL + process.env.VUE_APP_EDIT_INFO,{headers: headers})
.then(response => {
commit('authenticateUser');
commit('setUserInfo', response.data.result);
resolve();
})
.catch(error => {
console.log(error);
reject();
})
});
}
},
Login.vue:
async login () {
let self = this;
axios.post(process.env.VUE_APP_BASE_URL + process.env.VUE_APP_LOGIN,
this.loginInfo
).
then(function (response) {
await this.$store.dispatch('loadUserInfo').then((res)=>{
this.$emit('authenticateUser', true);
this.$emit('registeredIdentification', self.$store.getters.getUsername)
this.$router.push({ name: 'mainBox' })
});
localStorage.setItem('access_token', response.data.result.access_token)
localStorage.setItem('refresh_token', response.data.result.refresh_token)
})
.catch(function (error) {
// let statusCode = error.response.status;
console.log(error);
});
}
try moving the async declaration so it is "inside" the then:
async login () {
...
.then(async function (response) {
await this.$store.dispatch('loadUserInfo').then((res)=>{
...
}
Using then with async/await may be unnecessary:
async login() {
try {
const loginUrl = process.env.VUE_APP_BASE_URL + process.env.VUE_APP_LOGIN;
const { data } = await axios.post(loginUrl, this.loginInfo)
const { access_token: accessToken, refresh_token: refreshToken } = data.result;
await this.$store.dispatch('loadUserInfo');
this.$emit('authenticateUser', true);
this.$emit('registeredIdentification', this.$store.getters.getUsername)
this.$router.push({ name: 'mainBox' })
localStorage.setItem('access_token', accessToken)
localStorage.setItem('refresh_token', refreshToken)
} catch (error) {
console.log(error);
}
}

Async/Await in fetch() how to handle errors

I have stripe async code in my React app, and trying to add error handling in my code but have no idea how to handle it. i know how to do it with .then() but async/await is new to me
EDITED
added .catch() i got errors in network tab in response tab.
but i can log it to console?
submit = async () => {
const { email, price, name, phone, city, street, country } = this.state;
let { token } = await this.props.stripe
.createToken({
name,
address_city: city,
address_line1: street,
address_country: country
})
.catch(err => {
console.log(err.response.data);
});
const data = {
token: token.id,
email,
price,
name,
phone,
city,
street,
country
};
let response = await fetch("/charge/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).catch(err => {
console.log(err.response.data);
});
console.log(response);
if (response.ok)
this.setState({
complete: true
});
};
thanks
Fetch detects only network errors. Other errors (401, 400, 500) should be manually caught and rejected.
await fetch("/charge/pay", headers).then((response) => {
if (response.status >= 400 && response.status < 600) {
throw new Error("Bad response from server");
}
return response;
}).then((returnedResponse) => {
// Your response to manipulate
this.setState({
complete: true
});
}).catch((error) => {
// Your error is here!
console.log(error)
});
If you are not comfortable with this limitation of fetch, try using axios.
var handleError = function (err) {
console.warn(err);
return new Response(JSON.stringify({
code: 400,
message: 'Stupid network Error'
}));
};
var getPost = async function () {
// Get the post data
var post = await (fetch('https://jsonplaceholder.typicode.com/posts/5').catch(handleError));
// Get the author
var response = await (fetch('https://jsonplaceholder.typicode.com/users/' + post.userId).catch(handleError));
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
};
You can either use try/catch just like normal, imperative programming:
try {
let response = await fetch("/charge/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
} catch(error) {
// Error handling here!
}
Or you can mix-and-match .catch() just like you do with promises:
let response = await fetch("/charge/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).catch(function(error) {
// Error handling here!
});
Wrap your await with try catch.
try {
let response = await fetch("/charge/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
console.log(response);
} catch (error) {
console.log(error);
}
This works if server returns { message: "some error" } but I'm trying to get it to support res.statusText too:
const path = '/api/1/users/me';
const opts = {};
const headers = {};
const body = JSON.stringify({});
const token = localStorage.getItem('token');
if (token) {
headers.Authorization = `Bearer ${token}`;
}
try {
const res = await fetch(path, {
method: opts.method || 'GET',
body,
headers
});
if (res.ok) {
return await (opts.raw ? res.text() : res.json());
}
const err = await res.json();
throw new Error(err.message || err.statusText);
} catch (err) {
throw new Error(err);
}
async function loginWithRedirect(payload: {
username: string;
password: string;
}) {
const resp = await (await fetch(`${env.API_URL}/api/auth/login`, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(payload),
credentials: "include",
})).json();
if (resp.error) {
dispatch({type: "ERROR", payload: resp.error.message});
} else {
dispatch({type: "LOGIN", payload: resp});
}
}
If response.ok is false you can throw an error then chain catch method after calling your function as follows
async function fetchData(){
const response = await fetch("/charge/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
if(!response.ok){
const message = `An error occured: ${response.status}`;
throw new Error(message);
}
const data = await response.json();
return data;
}
fetchData()
.catch(err => console.log(err.message));
I write promise function for using fetch in async await.
const promisyFetch = (url, options) =>
new Promise((resolve, reject) => {
fetch(url, options)
.then((response) => response.text())
.then((result) => resolve(result))
.catch((error) => reject(error));
});
By the way i can use it easly in async with try catch
const foo = async()=>{
try {
const result = await promisyFetch('url' requestOptions)
console.log(result)
} catch (error) {
console.log(error)
}
}
It was simple example, you could customize promisyFetch function and request options as you wish.
const data = {
token: token.id,
email,
price,
name,
phone,
city,
street,
country
};
axios
.post("/charge/pay", data)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err.response.data);
});

Categories

Resources