Created
January 2, 2017 11:16
-
-
Save bs1180/9ceb921b62f4156335faa3bfa8b910cc to your computer and use it in GitHub Desktop.
Apollo HOC component
This file contains hidden or 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 'isomorphic-fetch' | |
import { getDataFromTree, ApolloProvider } from 'react-apollo/lib/index' | |
import { ApolloClient, createNetworkInterface } from 'apollo-client' | |
import { createStore, combineReducers, applyMiddleware, compose } from 'redux'; | |
import { omit } from 'lodash' | |
const isServer = (typeof window === 'undefined') | |
const makeClient = () => new ApolloClient({ | |
ssrMode: true, | |
dataIdFromObject: o => o._id, | |
networkInterface: createNetworkInterface({ | |
uri: 'https://graphql.nmr.io/graphql' | |
}) | |
}) | |
const initClient = () => { | |
if (isServer) { | |
return makeClient() | |
} else { | |
if (!window.client) { | |
window.client = makeClient() | |
} | |
return window.client | |
} | |
} | |
const makeStore = (client, initialState = {}) => | |
createStore( | |
combineReducers({ | |
apollo: client.reducer(), | |
}), | |
initialState, | |
compose( | |
applyMiddleware(client.middleware()), | |
isServer ? f => f: window.devToolsExtension ? window.devToolsExtension() : f => f, | |
) | |
); | |
const initStore = (client, initialState) => { | |
if (isServer) { | |
return makeStore(client, initialState) | |
} else { | |
if (!window.store) { | |
window.store = makeStore(client, initialState) | |
} | |
return window.store | |
} | |
} | |
export default Component => class Apollo extends React.Component { | |
static async getInitialProps () { | |
const client = initClient() | |
const store = initStore(client) | |
const app = React.createElement(ApolloProvider, { client, store }, React.createElement(Component)) | |
await getDataFromTree(app) | |
const initialState = {[client.reduxRootKey]: { | |
data: client.store.getState()[client.reduxRootKey].data | |
}} | |
return { initialState } | |
} | |
constructor (props) { | |
super(props) | |
this.client = initClient() | |
this.store = initStore(this.client, this.props.initialState) | |
} | |
render () { | |
return (<ApolloProvider client={this.client} store={this.store}> | |
<Component {...this.Props} /> | |
</ApolloProvider>) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment