Unverified Commit 154c4958 authored by Luis Alvarez D's avatar Luis Alvarez D Committed by GitHub

[Examples] Move with-relay-modern to SSG (#13882)

Related to https://github.com/vercel/next.js/issues/11014
parent 1c91a46c
RELAY_ENDPOINT=https://api.graph.cool/relay/v1/next-js-with-relay-modern-example
NEXT_PUBLIC_RELAY_ENDPOINT=https://api.graph.cool/relay/v1/next-js-with-relay-modern-example
......@@ -2,8 +2,6 @@
[Relay Modern](https://relay.dev/) is a new version of Relay designed from the ground up to be easier to use, more extensible and, most of all, able to improve performance on mobile devices. Relay Modern accomplishes this with static queries and ahead-of-time code generation.
In this simple example, we integrate Relay Modern seamlessly with Next by wrapping our _pages_ inside a [higher-order component (HOC)](https://facebook.github.io/react/docs/higher-order-components.html). Using the HOC pattern we're able to pass down a query result data created by Relay into our React component hierarchy defined inside each page of our Next application. The HOC takes `options` argument that allows to specify a `query` that will be executed on the server when a page is being loaded.
This example relies on [graph.cool](https://www.graph.cool) for its GraphQL backend.
## Deploy your own
......
import React from 'react'
import { createFragmentContainer, graphql } from 'react-relay'
const BlogPostPreview = ({ post }) => <li>{post.title}</li>
......
import React from 'react'
import { createFragmentContainer, graphql } from 'react-relay'
import BlogPostPreview from './BlogPostPreview'
......
import { useMemo } from 'react'
import { Environment, Network, RecordSource, Store } from 'relay-runtime'
let relayEnvironment = null
let relayEnvironment
// Define a function that fetches the results of an operation (query/mutation/etc)
// and returns its results as a Promise:
// and returns its results as a Promise
function fetchQuery(operation, variables, cacheConfig, uploadables) {
return fetch(process.env.RELAY_ENDPOINT, {
return fetch(process.env.NEXT_PUBLIC_RELAY_ENDPOINT, {
method: 'POST',
headers: {
Accept: 'application/json',
......@@ -18,27 +19,32 @@ function fetchQuery(operation, variables, cacheConfig, uploadables) {
}).then((response) => response.json())
}
export default function initEnvironment({ records = {} } = {}) {
// Create a network layer from the fetch function
const network = Network.create(fetchQuery)
const store = new Store(new RecordSource(records))
function createEnvironment(initialRecords) {
return new Environment({
// Create a network layer from the fetch function
network: Network.create(fetchQuery),
store: new Store(new RecordSource()),
})
}
// Make sure to create a new Relay environment for every server-side request so that data
// isn't shared between connections (which would be bad)
if (typeof window === 'undefined') {
return new Environment({
network,
store,
})
}
export function initEnvironment(initialRecords) {
// Create a network layer from the fetch function
const environment = relayEnvironment ?? createEnvironment(initialRecords)
// reuse Relay environment on client-side
if (!relayEnvironment) {
relayEnvironment = new Environment({
network,
store,
})
// If your page has Next.js data fetching methods that use Relay, the initial records
// will get hydrated here
if (initialRecords) {
environment.getStore().publish(new RecordSource(initialRecords))
}
// For SSG and SSR always create a new Relay environment
if (typeof window === 'undefined') return environment
// Create the Relay environment once in the client
if (!relayEnvironment) relayEnvironment = environment
return relayEnvironment
}
export function useEnvironment(initialRecords) {
const store = useMemo(() => initEnvironment(initialRecords), [initialRecords])
return store
}
import React from 'react'
import initEnvironment from './createRelayEnvironment'
import { fetchQuery, ReactRelayContext } from 'react-relay'
export default function withData(ComposedComponent, options = {}) {
return class WithData extends React.Component {
static displayName = `WithData(${ComposedComponent.displayName})`
static async getInitialProps(ctx) {
// Evaluate the composed component's getInitialProps()
let composedInitialProps = {}
if (ComposedComponent.getInitialProps) {
composedInitialProps = await ComposedComponent.getInitialProps(ctx)
}
let queryProps = {}
let queryRecords = {}
const environment = initEnvironment()
if (options.query) {
// Provide the `url` prop data in case a graphql query uses it
// const url = { query: ctx.query, pathname: ctx.pathname }
const variables = {}
// TODO: Consider RelayQueryResponseCache
// https://github.com/facebook/relay/issues/1687#issuecomment-302931855
queryProps = await fetchQuery(environment, options.query, variables)
queryRecords = environment.getStore().getSource().toJSON()
}
return {
...composedInitialProps,
...queryProps,
queryRecords,
}
}
constructor(props) {
super(props)
this.environment = initEnvironment({
records: props.queryRecords,
})
}
render() {
return (
<ReactRelayContext.Provider
value={{ environment: this.environment, variables: {} }}
>
<ComposedComponent {...this.props} />
</ReactRelayContext.Provider>
)
}
}
}
require('dotenv').config()
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
webpack: (config) => {
config.plugins = config.plugins || []
config.plugins = [
...config.plugins,
// Read the .env file
new Dotenv({
path: path.join(__dirname, '.env'),
systemvars: true,
}),
]
return config
},
}
{
"name": "with-relay-modern",
"version": "3.0.4",
"description": "Example of Next.js with Relay Modern SSR",
"version": "1.0.0",
"description": "Example of Next.js with Relay Modern",
"scripts": {
"graphcool-init": "graphcool init --schema schema/init-schema.graphql",
"dev": "next",
......@@ -10,11 +10,8 @@
"relay": "relay-compiler --src ./ --exclude '**/.next/**' '**/node_modules/**' '**/test/**' '**/__generated__/**' --exclude '**/schema/**' --schema ./schema/schema.graphql",
"schema": "graphql get-schema -e dev"
},
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^8.2.0",
"dotenv-webpack": "^1.7.0",
"graphql": "^14.6.0",
"next": "latest",
"react": "^16.13.0",
......
import { ReactRelayContext } from 'react-relay'
import { useEnvironment } from '../lib/relay'
export default function App({ Component, pageProps }) {
const environment = useEnvironment(pageProps.initialRecords)
return (
<ReactRelayContext.Provider value={{ environment, variables: {} }}>
<Component {...pageProps} />
</ReactRelayContext.Provider>
)
}
import Link from 'next/link'
export default function About() {
return (
<div>
<Link href="/">
<a>Home</a>
</Link>
<p>This is the about page</p>
</div>
)
}
import withData from '../lib/withData'
import Link from 'next/link'
import { fetchQuery } from 'react-relay'
import { initEnvironment } from '../lib/relay'
import BlogPosts from '../components/BlogPosts'
import indexPageQuery from '../queries/indexPage'
const Index = ({ viewer }) => (
<div>
<Link href="/about">
<a>About</a>
</Link>
<BlogPosts viewer={viewer} />
</div>
)
export default withData(Index, {
query: indexPageQuery,
})
export async function getStaticProps() {
const environment = initEnvironment()
const queryProps = await fetchQuery(environment, indexPageQuery)
const initialRecords = environment.getStore().getSource().toJSON()
return {
props: {
...queryProps,
initialRecords,
},
}
}
export default Index
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment