Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map an array with getServerSideProps in NextJS?

I am trying to use the data retrieved from the Twitch API to create a list of streamers. But when I try to map the props from getServerSideProps I get a blank page. If I console.log, I get all the data, but on mapping, I get nothing.

I am using the following code:

export default function Home( { users } ) {

  console.log(users);
  
  return (
    <div>
      <Head>
        <title>Twitch</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

     
      <div className=''>
       {users.map((user) => (
         <div key={user.id}>
            <h1>{user.display_name}</h1>
        </div>
        ))}
      </div>
    </div>
  )
}

            
            
export async function getServerSideProps() {
  const res = await fetch('http://localhost:3000/api/users')
  const data = await res.json()
  const [users] = await Promise.all([data])
  return {
      props: {
          users
      }
  }
}

The console.log returns:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(3) [{…}, {…}, {…}]
0: {data: Array(1)}
1: {data: Array(1)}
2: {data: Array(1)}

>Solution :

I think we should check back to what the data looks like in your console log.

(3) [{…}, {…}, {…}]
0: {data: Array(1)}
1: {data: Array(1)}
2: {data: Array(1)}

See anything against your template that might not be returning what you think it is?

I see a list of objects with a data array, so potentially your template code may look more like:

{users.map((user) => (
  <div key={user.data[0].id}>
    <h1>{user.data[0].display_name}</h1>
  </div>
))}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading