简体   繁体   中英

request an array of endpoints from an API

Hello how can someone call a list of specific names (endpoints) from an API in Javascript (ES6)? For example one endpoint is of the API is:

http://yugiohprices.com/api/card_data/one%20for%20one


{
    "status": "success"
  , "data": {
      "name": "One for One"
    , "text": "Send 1 monster from your hand to the Graveyard; Special Summon 1 Level 1 monster from your hand or Deck."
    , "card_type": "spell"

  }
}

For retrieving the above data by using a list of names, how should be implemented? Is it possible to use a for loop with a nested fetch for every name's data that should be retrieved? Like the following example:

Array:

array = JSON.stringify([ { 'name' : 'One for One'},
                         { 'name' : 'Reasoning'},
                                  ...
                       ]);

And then use a for loop with a nested fetch

for(let name of array){
   fetch('http://yugiohprices.com/api/card_data/name').then(results => {
     return results.json(); }).then(card =>{
      let card_name = card.data.map((name) => {  return( <div key={name.name}> {name.text} </div> )    })

I have made the following example. It can be run directly in a browser. I hope this will answer your question and resolve your issue.

fetchfromAPI.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script type="text/babel">
let array = [ { 'name' : 'One for One'},{ 'name' : 'Reasoning'}];
var proxyUrl = 'https://cors-anywhere.herokuapp.com/';
class Cards extends React.Component {
   constructor(props){
     super(props);
     this.state = {
       cards: []
     }
   }
    componentWillMount(){
        for(let a of array) 
   {

    fetch(proxyUrl+'http://yugiohprices.com/api/card_data/'+a.name).then(results => {
        return results.json()}).then((card) => {
                var currentCards = this.state.cards;
                currentCards.push(card.data)
                this.setState({'cards': currentCards});
    }
   )
    }
   }
   render(){
     const list = this.state.cards.map((card)=>{
         return(<li key={card.name}><b>{card.name}</b>:{card.text}</li>);
     })
    return(<ul>{list}</ul>);
  }
}

ReactDOM.render(<Cards />, document.getElementById('root'));
</script>
<div id="root"></div>

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