Recommand · June 7, 2021 0

Displaying Data from Javascript Fetch API – Question

I am new to working with APIs in javascript. I am looking to get input that a user puts into a box on a site (a city name) and fetch the API, to retrieve the temperature in that city. So far I have the following to fetch the API. But I am a bit lost on how to actually get that data and display it. How would I get the ‘data’? I’m just not used to using APIs with Javascript and looking to learn more.

js file:

function hi() {

  function temperature(input) {
  const myKey = "Hidden_for_privacy";
  const api = ` 

      let data = response.json();
      return data;

Then I have this. searchUser is just representing the location the user types in:

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

Relevant HTML:

 <div class="container searchContainer">
            <div class="search card card-body">
                <h3>Get The Weather For a Location</h3>
                <p class="lead">Enter Your Location</p>
                <input type="text" id="searchUser" class="form-control" 
            <div id="profile"></div>
        <div class="container text-center mt-2">
            <button class="btn btn-primary" id="submit">Submit</button>
        <div id="content">

I think you have a few syntax errors going on before you can get into displaying data on the screen. I’d suggest concentrating on the JS implementation first to ensure you are successfully fetching data and loading it to the console. For instance, the closures in your JS might be causing problems. The hi function is creating a closure and then you are passing an argument of input into a function inside it but there is no local variables for it to grab.

Maybe try something like this to start and see what it logs:

function getTemperature() {
  const myKey = "Hidden_for_privacy";
  const api = ` 

  // .json returns a promise so you need to use .then to get the data from it synchronously
    .then((response) => response.json())
    .then(data => console.log(data))