Next.js hook for using external data with SSR The difference with 'getStaticProps' is that the same code can be used for both the server and the client when receiving external data.
- Use App.getInitialProps to receive the fetch data generated by the component
_app.tsx
import { CachesType, createCache, getDataFromTree } from '@react-libraries/use-ssr'
import { AppContext, AppProps } from 'next/app'
const App = (props: AppProps & { cache: CachesType }) => {
const { Component, cache } = props
createCache(cache)
return <Component />
}
App.getInitialProps = async ({ Component, router, AppTree }: AppContext) => {
const cache = await getDataFromTree(
<AppTree Component={Component} pageProps={{}} router={router} />
)
return { cache }
}
export default App
- pages/index.tsx
import React from 'react'
import { useSSR } from '@react-libraries/use-ssr'
const Page = () => {
const [state, setState] = useSSR(
['weather', '130000'] /*CacheKeyName*/,
async (state, setState) => {
// When this function finishes, the server side will finish processing and SSR will be performed.
if (state !== undefined) return
setState(null)
const result = await fetch(
'https://www.jma.go.jp/bosai/forecast/data/overview_forecast/130000.json'
)
setState(result.json())
}
)
return (
<div>
<button onClick={() => setState(undefined)}>Reload</button>
<pre>{JSON.stringify(state, undefined, ' ')}</pre>
</div>
)
}
export default Page