1

I am new to using Javascript APIs and I'm trying to learn more about the different ways to write fetch. This uses the async await and Fetch class. I want to rewrite it without this, to look more like this:

function hi() {

  function temperature(input) {
  const myKey = "c3feef130d2c6af1defe7266738f7ca0";
  const api = `https://api.openweathermap.org/data/2.5/weather? 
q=${input}&lang=en&&appid=${myKey}&units=metric`;

  fetch(api)
  .then(function(response){
      let data = response.json();
      console.log(data);
      return data;
  })

Currently I have this, using await and async, and the Fetch class:

function hi() {
  class Fetch {

    async getCurrent(input) {
      const myKey = "c3feef130d2c6af1defe7266738f7ca0";
      //make request to url
      const response = await fetch(
      `https://api.openweathermap.org/data/2.5/weather? 
  q=${input}&lang=en&&appid=${myKey}&units=metric`
      );

      const data = await response.json();
      console.log(data);
      return data;
    }}
  // ui.js

  class UI {
    constructor() {
      this.uiContainer = document.getElementById("content");
      this.city;
      this.defaultCity = "London";
    }

    populateUI(data) {
      //de-structure vars

      //add them to inner HTML

      this.uiContainer.innerHTML = `
      
   <div class="card mx-auto mt-5" style="width: 18rem;">
              <div class="card-body justify-content-center">
                  <h5 class="card-title">${data.name}</h5>
                  <h6 class="card-subtitle mb-2 text-muted">Highs of 
${data.main.temp_max}. Lows of ${data.main.temp_min}</h6>
                  <p class="card-text ">Weather conditions are described 
 as: ${data.weather[0].description}</p>
                  <p class="card-text ">Feels like: 
${data.main.feels_like}</p>

                  <p class="card-text ">Wind speed: ${data.wind.speed} 
m/s</p>
              </div>
          </div>
          `;
    }

    clearUI() {
      uiContainer.innerHTML = "";
    }

    saveToLS(data) {
      localStorage.setItem("city", JSON.stringify(data));
    }

    getFromLS() {
      if (localStorage.getItem("city" == null)) {
         return this.defaultCity;
  
      } else {
        this.city = JSON.parse(localStorage.getItem("city"));
      }
      return this.city;
    }

    clearLS() {
      localStorage.clear();
    }}


  //inst classes// original capstone.js starts here

  const ft = new Fetch();
  const ui = new UI();

  const search = document.getElementById("searchUser");
  const button = document.getElementById("submit");
    button.addEventListener("click", () => {
      const currentVal = search.value;

     // document.querySelector('#temperature-value').innerHTML = 
`${currentVal}`; // added this

      ft.getCurrent(currentVal).then((data) => {
        //call a UI method//
        ui.populateUI(data);
        //call saveToLS
       ui.saveToLS(data);
      });
    });

    //event listener for local storage

   window.addEventListener("DOMContentLoaded", () => {
      const dataSaved = ui.getFromLS();
      ui.populateUI(dataSaved);
    });
    }

The main issue I'm having, is when I try to rewrite the bottom part, including the currentVal part after: const ft = new Fetch(); const ui = new UI();

I am lost as to how to have it evaluate with the data. Since const ft = new Fetch, I'm having trouble understanding how to re-write this without the Fetch class and make sure currentVal evaluates with the data. Any help is appreciated, I'm mainly just trying to learn more about how fetch works with API.

2
  • 1
    The question is confusing, in the title you say you want re-write Fetch API, in the text you want to re-write your code without Fetch class, what you actually need is not clear at all. That said, it's a huge job to re-write Fetch API, maybe you should find a bit smaller API for learning, and study Fetch API with tutorials and documentation ..? Commented Jun 10, 2021 at 4:52
  • You want it to look more like a function that contains a function that doesn't execute and returns nothing. Why? fetch works fine as it is. Commented Jun 10, 2021 at 4:55

1 Answer 1

1

This could be as simple as modifying your temperature function to:

function temperature(input) {
  const myKey = "<REDACTED>";
  const api = `https://api.openweathermap.org/data/2.5/weather?q=${input}&lang=en&appid=${myKey}&units=metric`;

  return fetch(api).then(function(response){
    let data = response.json();
    console.log(data);
    return data;
  });
}

and then, replace the call to ft.getCurrent with temperature:

temperature(currentVal).then((data) => {
  //call a UI method//
  ui.populateUI(data);
  //call saveToLS
  ui.saveToLS(data);
});

remove the creation of ft, and, in fact, remove the Fetch class altogether.

The return type of temperature is a Promise, which itself is the return of response.json(). The way that Promises work, returning a Promise inside the then continuation causes the invocation of then to return that Promise, allowing for chaining like that.

You'll notice that the:

console.log(data);

line inside temperature will actually output something like:

Promise { <state>: "pending" }

showing that it is, in fact, a Promise, but this also means that the logging is not very useful, and temperature could be further simplified to:

function temperature(input) {
  const myKey = "<REDACTED>";
  const api = `https://api.openweathermap.org/data/2.5/weather?q=${input}&lang=en&appid=${myKey}&units=metric`;

  return fetch(api).then(r => r.json());
}
Sign up to request clarification or add additional context in comments.

Comments

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.