Invalid hook call in getServerSideProps (Nextjs)

Viewed 7042
export const getServerSideProps: GetServerSideProps = async (context) => {
  const { isLoading, error, data } = useQuery('repoData', () =>
    fetch(
      'https://api.github.com/repos/tannerlinsley/react-query'
    ).then((res) => res.json())
  )
  console.log({ data })

  return {
    props: {
      data,
    },
  }

Although there are many questions related to react invalid hook call in stackoverflow but still none of them able to solve my problem.

3 Answers

You can't use hooks in getServerSideProps. Instead, you can fetch the data and pass it to the useQuery hook in your component as initial data as explained in the SSR docs:

export async function getStaticProps() {
  const posts = await getPosts()
  return { props: { posts } }
}

function Posts(props) {
  const { data } = useQuery('posts', getPosts, { initialData: props.posts })

  // ...
}

According to the official docs this is the correct way to do it.

const getPosts = () =>
  fetch('https://api.github.com/repos/tannerlinsley/react-query').then((res) =>
    res.json()
  )
export const getServerSideProps: GetServerSideProps = async (context) => {
  const queryCache = new QueryCache()

  await queryCache.prefetchQuery('posts', getPosts)

  return {
    props: {
      dehydratedState: dehydrate(queryCache),
    },
  }
}

Home Component

 const { data } = useQuery('posts', getPosts)

Is getServerSideProps a hook? If so, you must call it useServerSideProps.

(EDIT after @Patrick_Roberts comment, saying it is not a hook but a special function)

Then you cannot call useQuery (anything starting with use is considered a hook) in it… If useQuery is not a hook, then you should rename it. If it is an external function which cannot be renamed, simply disable the linter error for this line.

See https://en.reactjs.org/docs/hooks-rules.html

Related