Slide 37
Slide 37 text
3. SSR with Next.js
export const getServerSideProps = async (context) => {
const customerId = getCustomerId(context)
return {
props: {
preloadedQueries: {
customerDetailQuery: await getPreloadedQuery(
CustomerDetailConcreteQuery,
{
customerId,
}
),
},
},
}
}
function Hydrate({
Component,
props,
}: {
Component: NextComponentType
props: any
}) {
const environment = useRelayEnvironment()
const transformedProps = useMemo(() => {
if (props == null) {
return props
}
const { preloadedQueries, ...otherProps } = props
if (preloadedQueries == null) {
return props
}
const queryRefs = {}
for (const [queryName, { params, variables, response }] of Object.entries(
preloadedQueries
) as any) {
environment.getNetwork().responseCache.set(params.id, variables, response)
queryRefs[queryName] = {
environment,
fetchKey: params.id,
fetchPolicy: 'store-or-network',
isDisposed: false,
name: params.name,
kind: 'PreloadedQuery',
variables,
}
}
return { ...otherProps, queryRefs }
}, [environment, props])
return
}