Next.js: Cant use fetch for component

Created on 16 Jan 2019  路  2Comments  路  Source: vercel/next.js

Hi there.
long after the end of research I decided to use ssr for next. next is super for me.
but the trouble is that, when working in the following pages under the pages directory:

import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Index = (props) => (
  <Layout>
    <h1>Batman TV Shows</h1>
    <ul>
      {props.shows.map(({show}) => (
        <li key={show.id}>
          <Link as={`/p/${show.id}`} href={`/post?id=${show.id}`}>
            <a>{show.name}</a>
          </Link>
        </li>
      ))}
    </ul>
  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://api.tvmaze.com/search/shows?q=batman')
  const data = await res.json()

  console.log(`Show data fetched. Count: ${data.length}`)

  return {
    shows: data
  }
}

export default Index

components do not work under directory. What is the reason?

Most helpful comment

Next.js can only find _top level_ getInitialProps, meaning you always declare your data-fetching at the _page_ level.

but I have a part named sidebar. and I include this part in every page. I need to show the posts here. No other solution?

All 2 comments

Next.js can only find top level getInitialProps, meaning you always declare your data-fetching at the page level.

Next.js can only find _top level_ getInitialProps, meaning you always declare your data-fetching at the _page_ level.

but I have a part named sidebar. and I include this part in every page. I need to show the posts here. No other solution?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lixiaoyan picture lixiaoyan  路  3Comments

DvirSh picture DvirSh  路  3Comments

swrdfish picture swrdfish  路  3Comments

knipferrc picture knipferrc  路  3Comments

timneutkens picture timneutkens  路  3Comments