I'm new to React/NextJS and trying to do a simple fetching and whenever I try to use the map function it does not seem to go inside it. I'm not sure what I'm doing wrong, I'm following some tutorials/documentation NextJS Doc but I have no idea what I am missing. Can anyone give me some insight please?
This is all inside of a page.tsx file. src/app/incidents/page.tsx
async function getData() {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
if(!res.ok) {
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Incidents () {
const reports = await getData()
return(
<main>
{reports?.map((item: any) => {
<p className='text-orange-500'>Hello</p>
})}
</main>
)
}
Here are my dependencies in my package.json incase its helpful:
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.1.0"
},```
blank screen without expected results Like I mentioned and the code above, I tried just following the tutorials and documentations but I cannot seem to get it. My Screen just doesn't show anything (The image is black because Im using dark mode lol).
You can get the data. There is no return value in the Map function. Since you use {} in the map function, a code block is opened, since there is no return value in this block, rendering does not occur.
{reports.map((item) => (
<p>{item.name}</p>
))}
() You can show data on the screen using normal parentheses.
Revised version.
async function getData() {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
if (!res.ok) {
throw new Error("Failed to fetch data");
}
return res.json();
}
export default async function Incidents() {
const reports = await getData();
return (
<main>
{reports?.map((item) => (
<p className="text-orange-500">{item.name}</p>
))}
</main>
);
}