https://stackoverflow.com/questions/44182951/axios-chaining-multiple-api-requests
const tokenInput = JSON.stringify({
...
});
const Agent = new https.Agent({
rejectUnauthorized: false
})
// call for access token
const [tokenResponse] = await Promise.all([axios
.post(process.env.TOKEN_URL, tokenInput, {
httpsAgent: Agent,
headers: {
// Overwrite Axios's automatically set Content-Type
'Content-Type': 'application/json'
}
})
]);
// check token
const accessToken = tokenResponse.data.result.accessToken;
// check access token
if (!tokenResponse.data.result.accessToken) {
return;
}
/**
* prepare data to post
*/
const postData = JSON.stringify({
....
});
axios
.post(process.env.FORM_URL, postData, {
httpsAgent: Agent,
headers: {
// Overwrite Axios's automatically set Content-Type
'Content-Type': 'application/json'
}
})
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error)
})
First off, not sure you want to do this in your componentWillMount
, it's better to have it in componentDidMount
and have some default states that will update once done with these requests. Second, you want to limit the number of setStates you write because they might cause additional re-renders, here is a solution using async/await:
async componentDidMount() {
// Make first two requests
const [firstResponse, secondResponse] = await Promise.all([
axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=${this.props.p1}`),
axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=${this.props.p2}`)
]);
// Make third request using responses from the first two
const thirdResponse = await axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + firstResponse.data.results.place_id + '&destination=place_id:' + secondResponse.data.results.place_id + '&key=' + 'API-KEY-HIDDEN');
// Update state once with all 3 responses
this.setState({
p1Location: firstResponse.data,
p2Location: secondResponse.data,
route: thirdResponse.data,
});
}
Không có nhận xét nào:
Đăng nhận xét