Next.js Discord

Discord Forum

SSR rendering is not rendering the content

Answered
Tan posted this in #help-forum
Open in Discord
TanOP
I am trying to render simple post from an api. I was following LlamaDev tutorial. Here is the code :
import React from 'react';
// import styles from './page.module.css';
// import Link from 'next/link';
// import Image from 'next/image';

async function getData() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.

  // Recommendation: handle errors
  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data');
  }

  return res.json();
}

export default async function Page() {
  const data = await getData();
  return (
    <div>
      {data.map((d) => {
        <h1>d.title</h1>;
      })}
    </div>
  );
}

Its showing status ok. but I am seeing nothin in the browser.
Answered by Nelson
There are some mistakes in your code.
1. You need to return after mapping.
2. Use curly braces to evaluate the value of the title property of the object d.
3. You need to provide a unique key for each element.

Here is the correct version:
export default async function Page() {
  const data = await getData();
  return (
    <div>
      {data.map((d) => {
        return (
          <h1 key={d.id}>{d.title}</h1>
        )
      })}
    </div>
  );
}
View full answer

9 Replies

There are some mistakes in your code.
1. You need to return after mapping.
2. Use curly braces to evaluate the value of the title property of the object d.
3. You need to provide a unique key for each element.

Here is the correct version:
export default async function Page() {
  const data = await getData();
  return (
    <div>
      {data.map((d) => {
        return (
          <h1 key={d.id}>{d.title}</h1>
        )
      })}
    </div>
  );
}
Answer
@Tan Thank you so much!! I double checked the tutorial it hadn't returned there. But return worked in mine.
I think the difference in that tutorial and your code is the { vs (

data.map(item => (
  <Item item={item} key={item.id} />
))

works because this function does return the <Item>, but

data.map(item => { // <- { here not (
  <Item item={item} key={item.id} />
})

doesn't work because the function doesn't return anything
it's equivalent to
const add1 = (a, b) => a + b // works
const add2 = (a, b) => (
  a + b
) // works
const add3 = (a, b) => {
  a + b
} // doesn't work
np, it's quite hard to see the difference of ( and { if you don't have a font that differentiates them well
this discord font is an example of a bad font to use since ( and { looks so similar
@joulev np, it's quite hard to see the difference of `(` and `{` if you don't have a font that differentiates them well
TanOP
actually I replaced those because I prefer curly on the blocks rather than small brackets. I didn't even realized what I was doing. :blobsweats: