overclock
overclock

Reputation: 625

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:

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

Upvotes: 0

Views: 1114

Answers (1)

Clark Hinchcliff
Clark Hinchcliff

Reputation: 36

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>
))}

Upvotes: 1

Related Questions