skip to Main Content

I am working on creating a simple page that displays current free game giveaways using this API. https://gamerpower.p.rapidapi.com/api/giveaways?type=game&sort-by=popularity

However, I am still very new at working with APIs and am not sure if what I’ve been searching for is the right direction. The sources that I’ve been looking at haven’t made much sense, and any examples I’ve tried to follow still result in an Uncaught Reference error telling me that the variable I am trying to use isn’t defined.

Here is my very messy and basic code.

const gamesList = {
    method: 'GET',
    headers: {
        'X-RapidAPI-Key': '<API-KEY>',
        'X-RapidAPI-Host': 'gamerpower.p.rapidapi.com'
    }
};

fetch('https://gamerpower.p.rapidapi.com/api/giveaways?type=game&sort-by=popularity', gamesList)
    .then(response => response.json())
    .then(data => console.log(data.gamesList))
        let games=data
        document.querySelector('h2').innerText=data.gamesList.title
    .catch(err => console.error(err));
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="description" content="This is where your description goes">
        <meta name="keywords" content="one, two, three">

        <title>Game Giveaways</title>

        <!-- external CSS link -->
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>

        <h1>Current Game Giveaways</h1>
    
        <button type="button" name="button">Get Burger</button>

        <h2>Games</h2>
        <img src="" alt="">
        <h3>Description</h3>

        
        

        <script type="text/javascript" src="js/main.js"></script>
    </body>
</html>

I’m sure I am just missing something incredibly simple, but after working on it longer than I want to admit, I still can’t wrap my head around where I’m going wrong.

2

Answers


  1. The code that uses data needs to be inside the .then() callback. You have it after the callback.

    fetch('https://gamerpower.p.rapidapi.com/api/giveaways?type=game&sort-by=popularity', gamesList)
      .then(response => response.json())
      .then(data => {
        console.log(data.gamesList);
        document.querySelector('h2').innerText = data.gamesList.title;
      })
      .catch(err => console.error(err));
    Login or Signup to reply.
  2. Note: In the future, do not share your API key with anyone.

    You need to understand the response from the API call. I will demonstrate this to you using TypeScript types.

    The response of the /api/giveaways call is a Giveaway[] ("object array" or "array of objects").

    Here is a Giveaway object:

    interface Giveaway {
      description: string,
      end_date: string,          // 'YYYY-MM-DD HH:mm:ss' or 'N/A'
      gamerpower_url: string,    // URL
      id: number,
      image: string,             // Resource URI
      instructions: string,      // HTML
      open_giveaway: string,     // URL
      open_giveaway_url: string, // URL
      platforms: string,         // CSV
      published_date: string,    // 'YYYY-MM-DD HH:mm:ss' or 'N/A'
      status: string,            // e.g. 'Active'
      thumbnail: string,         // Resource URI
      title: string,
      type: string,              // e.g. 'Game'
      users: number,             // user count
      worth: string              // Currency in USD
    }
    

    Now that we understand the response of the API call, we know that we are dealing with an array of objects. Make sure that your second .then call is a function that contains all your success logic.

    fetch(url, options)
      .then((response) => response.json()) // parse JSON response
      .then((data) => {
        // do stuff with data (in this case an object[])
      })
      .catch((err) => console.error(err)); // handle errors
    

    Here is a "working" demo. All you need to do is supply a valid API key.

    const apiHost = 'gamerpower.p.rapidapi.com';
    const apiBaseUrl = `https://${apiHost}/api`
    const apiKey = '<API-KEY>';
    const defaultRequestConfig = {
      method: 'GET',
      headers: {
        'X-RapidAPI-Key': apiKey,
        'X-RapidAPI-Host': apiHost
      }
    };
    
    const endpoint = `${apiBaseUrl}/giveaways?type=game&sort-by=popularity`;
    fetch(endpoint, defaultRequestConfig)
      .then(response => response.json())
      .then(gamesList => {
        const ul = document.createElement('UL');
        gamesList.forEach(({ title }) => {
          ul.append(Object.assign(document.createElement('LI'), { innerText: title }));
        });
        document.querySelector('h2').after(ul);
      });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet"/>
    <h1>Current Game Giveaways</h1>
    <button type="button" name="button">Get Burger</button>
    <h2>Games</h2>
    <img src="" alt="">
    <h3>Description</h3>

    Here is the async/await version:

    (async() => {
      const endpoint = `${apiBaseUrl}/giveaways?type=game&sort-by=popularity`;
      const gamesList = await fetch(endpoint, defaultRequestConfig)
        .then(response => response.json());
      const ul = document.createElement('UL');
      gamesList.forEach(({ title }) => {
        ul.append(Object.assign(document.createElement('LI'), { innerText: title }));
      });
      document.querySelector('h2').after(ul);
    })();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search