Reputation: 113
I am following Indrik Lasn's React/Reflux/Thunk tutorial in React Native Training and having a hard time editing the code to allow for chained API calls.
Tutorial Link: https://medium.com/react-native-training/learn-how-to-build-a-rn-redux-cryptocurrency-app-chapter-iii-a454dda156b
How do I chain multiple API calls from coinmarketcap.com's API?
This is the code I thought would work. Developer tools shows the data is coming in for the 2 API calls but once the 2nd API loads into the browser, it replaces the data from the 1st API data within the view?
import axios from 'axios';
import { apiBaseURL } from './../Utils/Constants';
import {
FETCHING_COIN_DATA,
FETCHING_COIN_DATA_SUCCESS,
FETCHING_COIN_DATA_FAIL
} from './../Utils/ActionTypes';
export default function FetchCoinData() {
return dispatch => {
dispatch({ type: FETCHING_COIN_DATA })
axios.get(`${apiBaseURL}/v1/ticker/bitcoin`)
.then(res => dispatch({ type: FETCHING_COIN_DATA_SUCCESS, payload: res.data }))
.then(() => axios.get(`${apiBaseURL}/v1/ticker/litecoin`))
.then(res => dispatch({ type: FETCHING_COIN_DATA_SUCCESS, payload: res.data }))
.catch(err => {
dispatch({ type: FETCHING_COIN_DATA_FAIL, payload: err.data })
});
}
}
Upvotes: 0
Views: 2050
Reputation: 707
async componentDidMount() {
const firstRequest = await axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1);
const secondRequest = await axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2);
const thirdRequest = await axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + firstRequest.data.results.place_id + '&destination=place_id:' + secondRequest.data.results.place_id + '&key=' + 'API-KEY-HIDDEN');
this.setState({
p1Location: firstRequest.data,
p2Location: SecondRequest.data,
route: thirdRequest.data,
});
}
Upvotes: 1
Reputation: 2505
You can use async library to make the API calls all at the same time. You can also include a callback function which is invoked after the result from all the executed functions is received.
import async from "async";
async.parallel([
function(callback) {
axios.get(`${apiBaseURL}/v1/ticker/bitcoin`).then(res => callback(res));
},
function(callback) {
axios.get(`${apiBaseURL}/v1/ticker/ethereum`).then(res => callback(res));
}
], function(err, results) {
// after all the api calls are finished
const bitcoinRes = results[0];
const ethereumRes = results[1];
});
Upvotes: 0