Created
October 2, 2017 19:34
-
-
Save LawJolla/5fa01d54c64f1b17eea498b68068acab to your computer and use it in GitHub Desktop.
Gatsby + Apollo + Styled Components 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 { renderToString } from "react-dom/server"; | |
import ApolloClient, { createNetworkInterface } from "apollo-client"; | |
import { ApolloProvider, getDataFromTree } from "react-apollo"; | |
import { ServerStyleSheet, StyleSheetManager } from "styled-components"; | |
// function to generate hydrated state for client side Apollo | |
function makeApolloState(ssrClient) { | |
const state = { apollo: ssrClient.getInitialState() } | |
// appends apollo state to the global client window object | |
return ( | |
<script | |
dangerouslySetInnerHTML={{ | |
__html: `window.__APOLLO_STATE__=${JSON.stringify(state).replace( | |
/</g, | |
`\\u003c` | |
)};` | |
}} | |
/> | |
); | |
} | |
// Apollo Setup | |
const networkInterface = createNetworkInterface({ | |
uri: process.env.GRAPHCOOL_API | |
}); | |
// Apollo client in server side rendering mode | |
const client = new ApolloClient({ | |
ssrMode: true, | |
networkInterface, | |
dataIdFromObject: o => o.id | |
}); | |
exports.replaceRenderer = ({ | |
bodyComponent, | |
replaceBodyHTMLString, | |
setHeadComponents | |
}) => | |
new Promise((resolve) => { | |
// bodyComponent is the entire React component tree for the page | |
/* | |
to remove styled components: | |
1. remove const sheet | |
2. remove StyleSheetManager | |
3. remove sheet.getStyleElement from setHeadComponents array | |
*/ | |
const sheet = new ServerStyleSheet() | |
const ApolloQueries = ( | |
<ApolloProvider client={client}> | |
<StyleSheetManager sheet={sheet.instance}> | |
{bodyComponent} | |
</StyleSheetManager> | |
</ApolloProvider> | |
); | |
// getDataFromTree walks ApolloQueries tree for all Apollo GQL queries | |
// It runs the queries and mutates client object | |
getDataFromTree(ApolloQueries).then(() => { | |
// renders ApolloQueries to string and then inserts it into the page | |
replaceBodyHTMLString(renderToString(ApolloQueries)) | |
// sets head components with styled components and apollo state | |
setHeadComponents([sheet.getStyleElement(), makeApolloState(client)]) | |
resolve(); | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey i dont want to use the process.env.GRAPHCOOL_API
can i remove it or modify?