Getting multiple API requests using React Native

Here is the outline of my code (saving some details). Basically, I just want to make two similar API requests when I click a button and then have a function that works with the results of both requests, but I can't figure it out.

class myClass extends Component {

      constructor(props) {
        super(props);
        this.API_KEY_ONE = ‘firstapikey’
        this.API_KEY_TWO = ‘secondapikey’
        this.state = {
           city: 'undefined',
           state: 'undefined'
        }
      }

callOne() {
    this.REQUEST_URL = 'https://api.wunderground.com/api/' + this.API_KEY_ONE +    '/geolookup/conditions/astronomy/forecast/q/.json';

    fetch(this.REQUEST_URL).then((response) => response.json()).then((responseData)  => {

       this.setState({
        city: responseData.location.city
        });

    }).done();
}

 callTwo() {
      this.REQUEST_URL = 'https://api.DifferentSite.com/api/' + this.API_KEY_TWO +  '/geolookup/conditions/astronomy/forecast/q/.json';

      fetch(this.REQUEST_URL).then((response) => response.json()).then((responseData) => {

         this.setState({
        state: responseData.location.state
         });

     }).done();
}

// where to put this? when both requests finish, pass both to new component

this.props.navigator.push({
    title: 'Forecast',
    component: Forecast,
    passProps: {city: this.state.city, state: this.state.state}
  });


getForecast() {
     this.callOne();
     this.callTwo();
}

<TouchableHighlight onPress={() => this.getForecast()} />
+4
source share
2 answers

You can continue with .then(), so it should be something like this:

callBoth(){
    var request_1_url = 'https://api.wunderground.com/api/' + this.API_KEY_ONE +    '/geolookup/conditions/astronomy/forecast/q/.json';
    var request_2_url = 'https://api.DifferentSite.com/api/' + this.API_KEY_TWO +  '/geolookup/conditions/astronomy/forecast/q/.json';

    fetch(request_1_url).then((response) => response.json()).then((responseData)  => {
        this.setState({
            city: responseData.location.city
        });
    }).then(()=>{
        fetch(request_2_url).then((response) => response.json()).then((responseData) => {
         this.setState({
            state: responseData.location.state,
            isFinish: true
         });
     }).done();
    }).done();
}
+2
source

1) It seems that you are using cityand statehow passProps not intend to update CurrentView, so perhaps you should use them as a variable current component.

2) . set _finish = 0, city , _finish = _finish + 1 , _finish 2. state , .

fetch(...){
   // if _finish is equals 2, navigator push.
}

3) :

fetch(...){
   if (this._city && this._state){
      // navigator push
   }
}
0

Source: https://habr.com/ru/post/1611445/


All Articles