Reputation: 29
I'm trying build my first website that displays data from an api without a tutorial. Am I missing something?
I fetched the api correctly, the console log prints the data I need but when I try to display it, it gives me the games.map is not a function error.
'use client'
import React, { useEffect, useState } from 'react'
export default function Home() {
const [games, setGames] = useState([])
const apiKey = process.env.NEXT_PUBLIC_RAWG_API_KEY
const url = `https://rawg-video-games-database.p.rapidapi.com/games?key=${apiKey}`
useEffect(() => {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': process.env.NEXT_PUBLIC_RAPID_API_KEY,
'X-RapidAPI-Host': 'rawg-video-games-database.p.rapidapi.com',
},
}
fetch(url, options)
.then((response) => response.json())
.then((response) => {
console.log(response.results[0])
setGames(response.results[0])
})
.catch((err) => {
console.error(err)
})
}, [])
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
{games &&
games.map((game) => {
return (
<div key={game.id}>
<h1>{game.name}</h1>
</div>
)
})}
</main>
)
}
Upvotes: 1
Views: 328
Reputation: 1035
This error happens when the data is not an array and in this example for a high chance the data (response.results[0]
) is an object instead of an array.
Upvotes: 2