Last active
December 12, 2019 00:50
-
-
Save allpwrfulroot/ff1c16141677a95a4c410279c114df25 to your computer and use it in GitHub Desktop.
Moving the data fetch from render (useEffect) to SSR (getInitialProps)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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