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
The code that uses
data
needs to be inside the.then()
callback. You have it after the callback.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 aGiveaway[]
("object array" or "array of objects").Here is a
Giveaway
object: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.Here is a "working" demo. All you need to do is supply a valid API key.
Here is the
async
/await
version: