I'm trying to fetch an API into a state and using the map method to give a new array.
But it gives this error Uncaught ReferenceError data is not defined
Here's the code-
const [games,setGAMES] = React.useState([])
const [gamesList,setGamesList] = React.useState([])
React.useEffect(()=>{
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '68cd3db2f1mshf35a2b8ae04ad85p1fc5a1jsn0f05ed6a893a',
'X-RapidAPI-Host': 'free-to-play-games-database.p.rapidapi.com'
}
};
fetch('https://free-to-play-games-database.p.rapidapi.com/api/filter?tag=3d.mmorpg.fantasy.pvp&platform=pc', options)
.then(response => response.json())
.then( data => {setGAMES(data)})
setGamesList( data.map( (object) => {
return {
name: object.title,
link: object.game_url,
}
}))
},[])
setGamesList
function is being called out of the .then, this is causing the not defined
error.
Moved the function inside the block, this should work.
React.useEffect(()=>{
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '68cd3db2f1mshf35a2b8ae04ad85p1fc5a1jsn0f05ed6a893a',
'X-RapidAPI-Host': 'free-to-play-games-database.p.rapidapi.com'
}
};
fetch('https://free-to-play-games-database.p.rapidapi.com/api/filter?tag=3d.mmorpg.fantasy.pvp&platform=pc', options)
.then(response => response.json())
.then( data => {
setGAMES(data);
setGamesList( data.map( (object) => {
return {
name: object.title,
link: object.game_url,
}
}))
})
},[])