|
1 | 1 | importReactfrom'react' |
2 | 2 | import{renderToString}from'react-dom/server' |
| 3 | +import{ |
| 4 | +ApolloClient, |
| 5 | +createHttpLink, |
| 6 | +InMemoryCache, |
| 7 | +ApolloProvider, |
| 8 | +}from'@apollo/client' |
| 9 | +importfetchfrom'cross-fetch' |
| 10 | +import{getDataFromTree}from'@apollo/client/react/ssr' |
| 11 | + |
| 12 | +importReviewListfrom'../src/components/ReviewList' |
| 13 | + |
| 14 | +constapollo=newApolloClient({ |
| 15 | +link: createHttpLink({ |
| 16 | +uri: 'https://api.graphql.guide/graphql', |
| 17 | + fetch, |
| 18 | +}), |
| 19 | +ssrMode: true, |
| 20 | +cache: newInMemoryCache(), |
| 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 | | -constApp=()=><b>My server-rendered React app</b> |
| 25 | +constApp=()=>( |
| 26 | +<ApolloProviderclient={apollo}> |
| 27 | +<h1>Reviews:</h1> |
| 28 | +<ReviewListorderBy="createdAt_DESC"/> |
| 29 | +</ApolloProvider> |
| 30 | +) |
7 | 31 |
|
8 | 32 | exportdefault(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 | +constappHtml=renderToString( |
| 35 | +<divid="root"dangerouslySetInnerHTML={{__html: content}}/> |
| 36 | +) |
| 37 | +constinitialState=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