Search code examples
javascriptarraysapionsen-uionsen-ui2

PokeAPI - querying additional pokemon info


I'm currently learning how to use onsen.io and I'm using the PokiAPI to learn. I had helped earlier using "https://pokeapi.co/api/v2/pokemon?limit=151" to display the names of all 151 Pokemons in an ons-list thanks to @sandeep joshi.

I didn't know I need to make another query to be able to grab additional info like "abilities", "elements"..etc and I'm not sure how to do that, any help would be greatly appreciated!

Here's my code:

 <!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsenui.css">
  <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsen-css-components.min.css">
  <script src="https://unpkg.com/onsenui/js/onsenui.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
 <ons-navigator id="myNavigator" page="main-temp"></ons-navigator>
            
    <!-- ******************** main-template ******************** -->

    <template id="main-temp">
      <ons-page id="main-page">      
         <ons-toolbar style="background-color: red;">
          <div class="center" style="color: #fff;">Pokedex</div>
        </ons-toolbar>
      </ons-page>
   </template>

  <!-- ******************** list template ******************** -->
  
  <ons-page id="list-page">
    <div class="content content-container">
      <ons-list id="list-item"></ons-list>
    </div>
  </ons-page>

  <!-- ******************** spinner modal ******************** -->

  <ons-modal id="spinner-modal">
    <div style="margin: auto;">
      <ons-icon icon="md-spinner" size="100px" spin></ons-icon>
    </div>
  </ons-modal>
  
  </body>
  </html>

ons.ready(function() {
      
      var spinnerModal = document.querySelector('#spinner-modal');
      spinnerModal.show();

      var settings = {
        "url": `https://pokeapi.co/api/v2/pokemon?limit=151`,
        "method": "GET",
        "timeout": 0,
      };

      $.ajax(pokemonData)
        .done(function(result) {
          sendData(result.results); // result.results contains pokemon list :)

          let results = result;
          console.log(results);

        })
        .fail(function(xhr, status, error) {
          console.log('error:' + xhr.status);

        })
        .always(function() {

          spinnerModal.hide();
        })

      function sendData(jsonData) {
        var itemsList = document.getElementById('list-item'); // this is no longer null since this is no longer part of template.
        for (let i = 1; i < jsonData.length; i++) {

          itemsList.appendChild(
            ons.createElement(
              '<ons-card class="inside-cards">' +
              '<ons-list>' +

              '<ons-list-item modifier="tappable>' +
              '<div class="left" >' +
              jsonData[i].id +
              '</div>' +
              '<div class="" style="margin-left:20px;" >' +
              '<ons-icon icon="fa-canadian-maple-leaf"></ons-icon>' + ' ' + jsonData[i].url + "<br><br>" +
              '<ons-icon icon="fa-canadian-maple-leaf"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
              '<ons-icon icon="fa-canadian-maple-leaf"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
              '</div>' +

              '<div>' +
              '</div>' +
              '</ons-list-item>' +
              '</ons-list>' +
              '</ons-card>'
            )
          );
        }
      }

    })


Solution

  • I googled a little bit and found a great tutorial in plain javascript if you want to learn about pokedex application. here I got the information that to get the individual data about the pokemon you need to query the url with pokemon index number and not by the older way. so I have added some code by referencing the tutorial.

    some explanation.

    const promises = [];
      for (let i = 1; i <= 150; i++) {
        const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
        promises.push(fetch(url).then(res => res.json()));
      }
    

    this part fetches data for all 150 pokemons but API returns a promise so we are pushing all the promises in one array.

    Promise.all(promises).then(results => {
          const pokemon = results.map(data => ({
            name: data.name,
            id: data.id,
            image: data.sprites["front_default"],
            type: data.types.map(type => type.type.name).join(", "),
            ability: data.abilities.map(ability => ability.ability.name).join(','),
            moves: data.moves.map(move => move.move.name).slice(0, 10).join(', ')
          }));
          sendData(pokemon);
        })
    

    next once all the promises are resolved then we are using array.map function to iterate through each item from result and building our pokemon object(name,id, image, type, ability, moves) array which we are gonna use in our ons-list. I hope, I have explained as much as I could, but feel free to ask followup questions(if any) in comment.

    I have not done much with styling so the list may be looking ugly but since you are learning the Onsen-UI it will be good learning/task to build a great looking pokedex and show us all.

    ons.ready(function() {
    
      var spinnerModal = document.querySelector('#spinner-modal');
      spinnerModal.show();
    
      const promises = [];
      for (let i = 1; i <= 150; i++) {
        const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
        promises.push(fetch(url).then(res => res.json()));
      }
      Promise.all(promises).then(results => {
          const pokemon = results.map(data => ({
            name: data.name,
            id: data.id,
            image: data.sprites["front_default"],
            type: data.types.map(type => type.type.name).join(", "),
            ability: data.abilities.map(ability => ability.ability.name).join(','),
            moves: data.moves.map(move => move.move.name).slice(0, 10).join(', ')
          }));
          sendData(pokemon);
        })
        .catch((reason) => {
          if (reason === -999) {
            console.error("Had previously handled error");
          } else {
            console.error(`Trouble with promiseGetWord(): ${reason}`);
          }
        })
        .finally((info) => spinnerModal.hide());
    
      function sendData(jsonData) {
        debugger;
        var itemsList = document.getElementById('list-item'); // this is no longer null since this is no longer part of template.
        for (let i = 0; i < jsonData.length; i++) {
    
          itemsList.appendChild(
            ons.createElement(
              '<ons-card class="inside-cards"><ons-list><ons-list-header>' + jsonData[i].name + '</ons-list-header><ons-list-item modifier="tappable>' +
              '<div class="left" ></div><div class="" style="margin-left:20px;" ><ons-icon icon="fa-hashtag"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
              '<div class="right"><ons-icon icon="fa-thumbs-up"></ons-icon><img src=" ' + jsonData[i].image + '"></div>' + "<br><br>" +
              '<ons-icon icon="fa-user"></ons-icon> type :  ' + jsonData[i].type + "<br><br>" +
              '<ons-icon icon="fa-user"></ons-icon> Abilities :  ' + jsonData[i].ability + "<br><br>" +
              '<ons-icon icon="fa-user"></ons-icon> Moves/Attacks :  ' + jsonData[i].moves + "<br><br>" +
    
              '<div>' +
              '</div>' +
              '</ons-list-item>' +
              '</ons-list>' +
              '</ons-card>'
            )
          );
        }
      }
    
    })
    <!DOCTYPE html>
    <html>
    
    <head>
      <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsenui.css">
      <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsen-css-components.min.css">
      <script src="https://unpkg.com/onsenui/js/onsenui.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
    
    <body>
      <ons-navigator id="myNavigator" page="main-temp"></ons-navigator>
    
      <!-- ******************** main-template ******************** -->
    
      <template id="main-temp">
                <ons-page id="main-page">
                  
                       <ons-toolbar style="background-color: red;">
                        <div class="center" style="color: #fff;">Pokedex</div>
                      </ons-toolbar>
    
              </ons-page>
               </template>
    
      <!-- ******************** list template ******************** -->
    
    
      <ons-page id="list-page">
        <div class="content content-container">
          <ons-list id="list-item"></ons-list>
    
        </div>
      </ons-page>
      <!-- ******************** spinner modal ******************** -->
    
      <ons-modal id="spinner-modal">
        <div style="margin: auto;">
          <ons-icon icon="md-spinner" size="100px" spin></ons-icon>
        </div>
      </ons-modal>
    </body>
    
    </html>