Hi , i am a beginner and Need help with Array! on API call

I wrote code …Call API and display first 8 result on HTML,
I stuck with how to get 8 results to display because the code below is show all the results.

Thank you in advanced.
This is my code:

//Question 2

const url =
	"https://api.rawg.io/api/games?dates=2019-01-01,2019-12-31&ordering=-rating";

const resultsContainer = document.querySelector(".results");

async function createHTML() {
	try {
		const response = await fetch(url);
		const results = await response.json();
		//console.log(results.results);

		const dataLoops = results.results;

		for (let i = 0; i < dataLoops.length; i++) {
			const html = dataLoops
				.map((user) => {
					return `<div class = "result"> <p>Name: ${dataLoops[i].name}</p>
					 <p>Rating: ${dataLoops[i].rating}</p>
					  <p>Amount of tags: ${dataLoops[i].tags.length}</p></div>`;
				})
				.join("");
			if (i === 8) {
				break;
			}
			document.querySelector(".results").innerHTML = html;
		} //
	} catch (error) {
		resultsContainer.innerHTML = displayError(
			"An error occurred when calling the API"
		);
	}
	// } finally {
	// 	console.log("finally");
	// }
}
createHTML();

If I understand, you’re getting the first 20 elements and you only want the first 8?

You could slice off the elements you want, using the slice method. You could even chain it in there, like:

.slice(0, 8).map( // ...

thank you very much. i will try.

You fix me! Big thanks

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.