Created
July 13, 2020 03:07
-
-
Save AugustoCalaca/1f8dd7c630cb4522f9e94298aa7a255d to your computer and use it in GitHub Desktop.
inject query and variables to relay fectQuery on next ssr
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
import React from 'react'; | |
import { NextPage } from 'next'; | |
import { DocumentContext } from 'next/document'; | |
import { RelayEnvironmentProvider, fetchQuery } from 'react-relay/hooks'; | |
import { GraphQLTaggedNode, Variables } from 'relay-runtime'; | |
import { initEnvironment } from './createEnvironment'; | |
type OptionsWithData = { | |
query: GraphQLTaggedNode; | |
variables: Variables; | |
}; | |
const withData = (ComposedComponent: NextPage, options: OptionsWithData) => { | |
const WrappedComponent = ({ records, environment }) => { | |
const relayEnvironment = typeof window === 'undefined' ? environment : initEnvironment(records); | |
return ( | |
<RelayEnvironmentProvider environment={relayEnvironment}> | |
<ComposedComponent /> | |
</RelayEnvironmentProvider> | |
); | |
}; | |
WrappedComponent.getInitialProps = async (context: DocumentContext) => { | |
const isServer = !!context.req; | |
let composedInitalProps = {}; | |
if (ComposedComponent.getInitialProps) { | |
composedInitalProps = await ComposedComponent.getInitialProps(context); | |
} | |
if (!isServer) { | |
return { | |
...composedInitalProps, | |
environment: null, | |
}; | |
} | |
const environment = initEnvironment(); | |
const { query, variables } = options; | |
let records = {}; | |
if (query) { | |
await fetchQuery(environment, query, variables); | |
records = environment.getStore().getSource().toJSON(); | |
} | |
return { | |
...composedInitalProps, | |
records, | |
environment, | |
}; | |
}; | |
return WrappedComponent; | |
}; | |
export default withData; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment