0

I am trying to understand this Promise/fetch thing in js.

'use strict'
  const list = document.querySelector('.list');
    function test() {
      return fetch('https://swapi.dev/api/films/', {
        method: 'GET'
      });
    }      
    list.addEventListener('click', event => {
      console.log('TEST');
      alert("TEST");
     });
     test()
     .then( function(response) {
       return response.json();  
      })
      .then(function(data) {
        data.results.forEach(function(episode) {
        const ul = document.createElement('ul');
        ul.innerHTML = episode.title;
        list.append(ul); 
       })
     })
.list {
  cursor: pointer;
}

<ul class="list"></ul>

I need to from a drop-down list, from all the STAR WARS episodes(done), and more of that (the part where the troubles start) by click on the episode it must return a list of ships, used in the episode.

As you can see from the link code above - I was able to return the list of episodes correctly, but I just don't know how to create the drop-down menu currently I'm out of ideas, should I make a ul-li list, where ul - episodes and ul - ships?

Kinda hard for me to figure this one out, please Obi-van, you are my last hope.

1 Answer 1

2

Firstly what you've done is not a dropdown but a regular list. Use <select> tag.

  <select id="episodes" class="list"></select>

Then just add another element into the markup:

  <select id="ships" class="list"></select>

Then go to your api documentation and check what it can offer. Firstly let's see what you receive from your endpoint /films/: https://swapi.dev/documentation#films Obviously here you can find titles of each episode. Done by you. But you can also notice that the response has a list of links to starships endpoint. That's what you need for your second list.

  1. Getting ships: There're plenty of ways but let's take the easiest one. Luckily your api offers you a way to search an episode by title (https://swapi.dev/documentation#search). let's build request url:
const nameOfEpisode = event.target.value;
const requestUrl = "https://swapi.dev/api/films/?search=${nameOfEpisode}";
  1. Now we need a click handler. But before implementing it let's to refactor your test() function by giving it a proper name and making it more general so you could reuse it for both requests:
function apiGetRequest(url) {
  return fetch(url, method: 'GET').then(response => response.json())
}
  1. Now click handler:
function requestShips(event) {
  const nameOfEpisode = event.target.value;
  const requestUrl = `https://swapi.dev/api/films/?search=${nameOfEpisode}`;
  apiGetRequest(requestUrl).then(data => {
    const { starshipsUrls } = data[0];
    return starshipsUrls;
   }).then(requestStartshipNames)
   .then(renderStartshipList);
 }
  1. Implementing requestStartshipNames will involve several requests (one request per each starshipUrl). To get all the data synchronously let's use Promise.all:
function requestStartshipNames(starshipUrls){
  return Promise.all(starshipUrls.map(url => apiGetRequest(url)));
}
  1. Now to render the starships list you'll need to implement renderStartshipList function:
function renderStartshipList(starships){
  const startShipsList = document.querySelector('#ships');
  const starcheepsNames = starships.map(({ name }) => {
    const option = document.createElement('option');
    option.innerHTML = name;
    startShipsList.append(option); 
 })            
}

Of course you'll need to refactor your own code in order to match it with the new apiGetRequest utility function, new click handler and the new markup.

Good luck!

Sign up to request clarification or add additional context in comments.

4 Comments

Thx a lot! And if I want to build a regular list with ships-of-the-episode click event I should just avoid first part with the select tag and stick to your plan and refactor my code, correct?
I also getting warning at this part `` return fetch(url, method: 'GET').then(response => response.json()) }``
Tried to refactor my own code to work with it - doesn't work at all, ufortuantley.
@WizardRew what kind of warning?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.