|
1 | 1 | import React from 'react'
|
2 | 2 | import { renderToString } from 'react-dom/server'
|
| 3 | +import { |
| 4 | + ApolloClient, |
| 5 | + createHttpLink, |
| 6 | + InMemoryCache, |
| 7 | + ApolloProvider, |
| 8 | +} from '@apollo/client' |
| 9 | +import fetch from 'cross-fetch' |
| 10 | +import { getDataFromTree } from '@apollo/client/react/ssr' |
| 11 | + |
| 12 | +import ReviewList from '../src/components/ReviewList' |
| 13 | + |
| 14 | +const apollo = new ApolloClient({ |
| 15 | + link: createHttpLink({ |
| 16 | + uri: 'https://api.graphql.guide/graphql', |
| 17 | + fetch, |
| 18 | + }), |
| 19 | + ssrMode: true, |
| 20 | + cache: new InMemoryCache(), |
| 21 | +}) |
3 | 22 |
|
4 | 23 | // import App from '../src/components/App'
|
5 | 24 | // ^ this would result in errors, so we make a small example App:
|
6 |
| -const App = () => <b>My server-rendered React app</b> |
| 25 | +const App = () => ( |
| 26 | + <ApolloProvider client={apollo}> |
| 27 | + <h1>Reviews:</h1> |
| 28 | + <ReviewList orderBy="createdAt_DESC" /> |
| 29 | + </ApolloProvider> |
| 30 | +) |
7 | 31 |
|
8 | 32 | export default (req, res) => {
|
9 |
| - res.status(200).send(` |
10 |
| - <!doctype html> |
11 |
| - <html lang="en"> |
12 |
| -
|
13 |
| - <head> |
14 |
| - <meta charset="utf-8"> |
15 |
| - <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> |
16 |
| - <title>The GraphQL Guide</title> |
17 |
| - </head> |
18 |
| -
|
19 |
| - <body> |
20 |
| - <div id="root"> |
21 |
| - ${renderToString(<App />)} |
22 |
| - </div> |
23 |
| - </body> |
24 |
| -
|
25 |
| - </html> |
26 |
| -`) |
| 33 | + getDataFromTree(<App />).then((content) => { |
| 34 | + const appHtml = renderToString( |
| 35 | + <div id="root" dangerouslySetInnerHTML={{ __html: content }} /> |
| 36 | + ) |
| 37 | + const initialState = apollo.extract() |
| 38 | + |
| 39 | + res.status(200).send(` |
| 40 | + <!doctype html> |
| 41 | + <html lang="en"> |
| 42 | +
|
| 43 | + <head> |
| 44 | + <meta charset="utf-8"> |
| 45 | + <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> |
| 46 | + <title>The GraphQL Guide</title> |
| 47 | + </head> |
| 48 | +
|
| 49 | + <body> |
| 50 | + ${appHtml} |
| 51 | + <script> |
| 52 | + window.__APOLLO_STATE__=${JSON.stringify(initialState).replace( |
| 53 | + /</g, |
| 54 | + '\\u003c' |
| 55 | + )} |
| 56 | + </script> |
| 57 | + </body> |
| 58 | +
|
| 59 | + </html> |
| 60 | + `) |
| 61 | + }) |
27 | 62 | }
|
0 commit comments