Undefined message when trying to fetch my javascript from the console

Viewed 674

I seem to be getting a PromiseValue: undefined error for my "Visitor Count".

I am trying to get data from my API so it updates everytime i go on my website/visit the API link. My Lambda and API gateway are both set up properly but I think there is something wrong with my Javascript code which is why i get this undefined message.

Is anyone able to provide me some insight why I am getting this message and how i am able to resolve it?

Promise {<pending>}
 __proto__: Promise
   catch: ƒ catch()
   constructor: ƒ Promise()
   finally: ƒ finally()
   then: ƒ then()
   Symbol(Symbol.toStringTag): "Promise"
   __proto__: Object
   [[PromiseStatus]]: "resolved"
   [[PromiseValue]]: undefined

   Visitor Count:undefined

fetch('api link here')
   .then(function(sitevisits)
   {
       console.log("Visitor Count:" +
  sitevisits.visits);

  document.querySelector("#Visitors-text").innerHTML = "Total Visitors"+  
  sitevisits.visits;   
   });
2 Answers

fetch() returns a Promise which fulfills with Response object. To get the actual data from the Response object, you need to call Body.json() method on it. This method also returns a Promise, so you need to chain another then() function. Promise returned by .json() method will fulfill with the data from the API that you requested.

You should also chain a catch block at the end of the promise chain to catch and handle any errors that might occur during the HTTP request.

fetch('api link here')
   .then(response => response.json())       // call .json() method 
   .then(sitevisits => {
       console.log("Visitor Count:" + sitevisits.visits);

       document.querySelector("#Visitors-text")
               .innerHTML = "Total Visitors " + sitevisits.visits;   
   })
   .catch(error => console.log(error.message));

For details on how to make HTTP requests with fetch API, see MDN - Using Fetch

Exmaple:

See the following code snippet which shows you how to make an HTTP request with the fetch API.

In the following code snippet, a request is made to the jsonplaceholder API to fetch a single todo. When response is returned, in the first then block, we check if response status is 200 and if data returned by the API is in JSON format. If both these conditions are true, we call .json() method on the Response object othwerwise we throw an error to indicate that something went wrong.

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => {
    if (
        // check if response's status is 200
        response.ok &&
        // check if API return data is in JSON format
        response.headers.get('Content-Type').includes('application/json')
    ) {
      return response.json()
    } else {
      throw new Error('something went wrong');
    }
  })
  .then(data => console.log(data))
  .catch(error => console.log(error.message));

You might simply see what the API return in the network tab and check the HTTP status, in the dom inspector it could be a backend issue, etc. or maybe better define the HTTP method in request.

fetch ('api link here', 
  { 
    method: 'GET', 
    headers: { 
      'Accept': 'application / json', 
      'Content-Type': 'application / json' 
    }
  }) 
  .then ((response) => { 
    console.log (response); 
  }) 
  .catch ((error) => { 
    console .error (error); 
  });
Related