简体   繁体   中英

Multiple API requests using Axios ReactJS

y'all... I am trying to make multiple requests to stockTweet API with an array of endpoints, I have used a for loop to fire the requests. there should be a better way, searchTerm = [aapl, amzn. pypl] --- no restriction on number of terms.

https://api.stocktwits.com/api/2/streams/symbol/aapl.json

https://api.stocktwits.com/api/2/streams/symbol/amzn.json

https://api.stocktwits.com/api/2/streams/symbol/pypl.json

the number of requests is dynamic.

import React from 'react';
import axios from "axios";
import SearchBar from "./Searchbar";
import Card from "./Card";

const apiUrl = 'https://api.stocktwits.com/api/2/streams/symbol';
  const headers = {
    headers: {
      Accept: 'application/json',
    },
  };

class App extends React.Component{

  state = {};


    // --------------------------STATE--------------------------
    // {
    //     Apple.Inc: [
    //         {
    //             id: 111111,
    //             body: "aaaaaaaaaaa bbbbb ccccccc dddd",
    //             createdAt: timeStamp
    //         }
    //         {
    //             id: 222222,
    //             body: "aaaaaaaaaaa bbbbb ccccccc dddd",
    //             createdAt: timeStamp
    //         }
    //     ],
    //     Amazon.com: [
    //         {
    //             id: 333333,
    //             body: "aaaaaaaaaaa bbbbb ccccccc dddd",
    //             createdAt: timeStamp
    //         }
    //         {
    //             id: 444444,
    //             body: "aaaaaaaaaaa bbbbb ccccccc dddd",
    //             createdAt: timeStamp
    //         }
    //     ],
    // }


    onSearchSubmit = async (term) => {
      term = term.split(', ');
      for(let i = 0; i < term.length; i++){
        let symbol = term[i];
        const stocktwitsQuery = `${apiUrl}/${symbol}.json`;
        const resp = await axios.get(stocktwitsQuery, headers);
        let tweets = [];
        let allTweetsBody = res.data.messages.map((oneTweet) => tweets.push(oneTweet)); //add the tweet body to array
        this.setState({ ...this.state, [this.state[res.data.symbol['title']]]:  tweets });        
      }
    }


  render() {
    return( 
      <div className="ui container" style={{marginTop:'10px'}}>
          <SearchBar onSubmit={this.onSearchSubmit} />
      </div>
    );
  }

}

export default App;

How would I do that? TIA

PS Code is messed up..: :(

This should work for n number of terms. Just split the terms into array and pass it as argument into promise.all

const termUrls = terms.split(', ');
Promise.all(termsUrls).then((responses) => {
  console.log(response);
});

The downside of using promise.all in your case is that if one of your APIs is down so then your promise.all will reject all other ones. In your case, you could use promise.allSettled()

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either been fulfilled or rejected, with an array of objects that each describes the outcome of each promise.

It is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise.

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];

Promise.allSettled(promises).
  then((results) => results.forEach((result) =>  console.log(result.status)));

// expected output:
// "fulfilled"
// "rejected"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM