I’m fetching data using graphQL but wen I render in the page
it says Unhandled Runtime Error TypeError: events.map is not a function
useState don’t know if this correct?
const [events, setEvents] = useState < any > ([]);
const fetchEvents = async () => {
const requestBody = {
query: `
query{
events{
_id
title
date
price
description
creator {
_id
email
}
}
}
`
};
setLoading(true);
await fetch(`http://localhost:8888/graphql`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
}).then(res => {
if (res.status !== 200 && res.status !== 201) {
throw new Error('Failed!');
}
return res.json();
}).then(resData => {
//console.log(resData);
const events = resData.data.events;
setEvents({ events: events })
}).catch(err => {
console.log(err);
})
}
{
loading ? events.map((data: any, index: any) =>
<p key={index}>{data.title}</p>
)
:
<p>Loading</p>
}
>Solution :
You are getting "TypeError: events.map is not a function" error because events is an object, not an array. You are using setEvents({ events: events }) instead of setEvents(events) to set the state.
Changing setEvents({ events: events }) to setEvents(events) should fix it.
