caarlos0
caarlos0

Reputation: 20633

getInitialProps is never executed

I'm trying to make a Twitter component that loads the tweet from the twitter API and displays its HTML, which will be a <blockquote> and a <script> tag.

The advantage of this, if server side rendered, is that it would work even if the user has privacy settings that block the call to the twitter script: the user will still get the blockquote, which is better than the current behavior (shows nothing).

So, my idea was to do something like this:

import fetch from 'node-fetch'

function Tweet(props) {
  return <>
    <div dangerouslySetInnerHTML={{
      __html: props.__html
    }} />
    <p>here I am</p>
  </>
}

Tweet.getInitialProps = async ctx => {
  console.log("here I am on the road again")
  const res = await fetch(`https://api.twitter.com/1/statuses/oembed.json?id=${ctx.tweetId}`)
  const json = await res.json()
  return { __html: json.html }
}

export default Tweet

And then on the pages use it like <Tweet tweetId="blah" />.

I found two problems with my idea though:

  1. As per docs I cant access the tweetId property on getInitialProps
  2. getInitialProps is never called. The <p>here I am</p> appears on the HTML and the log is never printed anywhere.

So, my question is: what I am doing wrong? Is this even possible to do?

Thanks!

Upvotes: 1

Views: 113

Answers (1)

Michalis Garganourakis
Michalis Garganourakis

Reputation: 2930

As per Next.js documentation, getInitialProps can only be used to a page, and not in a component:

getInitialProps can only be added to the default component exported by a page, adding it to any other component won't work.

Upvotes: 3

Related Questions