Skip to content

Commit a10b80c

Browse files
committed
Add Apollo
1 parent 950bb8e commit a10b80c

File tree

1 file changed

+54
-19
lines changed

1 file changed

+54
-19
lines changed

‎server/api/server.js‎

Lines changed: 54 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,62 @@
11
importReactfrom'react'
22
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+
})
322

423
// import App from '../src/components/App'
524
// ^ 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+
)
731

832
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+
})
2762
}

0 commit comments

Comments
(0)