Skip to content

Instantly share code, notes, and snippets.

@allpwrfulroot
Last active December 12, 2019 00:50
Show Gist options
  • Save allpwrfulroot/ff1c16141677a95a4c410279c114df25 to your computer and use it in GitHub Desktop.
Save allpwrfulroot/ff1c16141677a95a4c410279c114df25 to your computer and use it in GitHub Desktop.
Moving the data fetch from render (useEffect) to SSR (getInitialProps)
Projects.getInitialProps = async ({ req }) => {
// Prevent unnecessary refetching
if (process.browser) {
const { projects } = window.__NEXT_DATA__.props.pageProps
if (projects && projects.length > 0) {
return { projects }
}
}
try {
// Have the correct API url
const pre = req
? `${req.headers['x-forwarded-proto'] || 'http'}://${req.headers[
'x-forwarded-host'
] || req.headers.host}`
: ''
const result = await fetch(`${pre}/api/get-projects`)
const { projects } = await result.json()
return { projects }
} catch (err) {
return {
projects: [],
error: err.message || 'Unavailable. Refresh page?',
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment