import React from "react";
import { initializeStore } from "../store";
const { store } = initializeStore();
const isServer = typeof window === "undefined";
const __NEXT_REDUX_STORE__ = "__NEXT_REDUX_STORE__";
function getOrCreateStore(initialState) {
// Always make a new store if server, otherwise state is shared between requests
if (isServer) {
return store;
}
// Create store if unavailable on the client and set it on the window object
if (!window[__NEXT_REDUX_STORE__]) {
window[__NEXT_REDUX_STORE__] = store;
}
return window[__NEXT_REDUX_STORE__];
}
export default App => {
return class AppWithRedux extends React.Component {
static async getInitialProps(appContext) {
// Get or Create the store with `undefined` as initialState
// This allows you to set a custom default initialState
const reduxStore = getOrCreateStore();
// Provide the store to getInitialProps of pages
appContext.ctx.reduxStore = reduxStore;
let appProps = {};
if (typeof App.getInitialProps === "function") {
appProps = await App.getInitialProps(appContext);
}
return {
...appProps,
initialReduxState: reduxStore.getState()
};
}
constructor(props) {
super(props);
this.reduxStore = getOrCreateStore(props.initialReduxState);
}
render() {
return <App {...this.props} reduxStore={this.reduxStore} />;
}
};
};
create file /page/_app.js
import App, { Container } from "next/app";
import React from "react";
import withApolloClient from "../lib/with-apollo-client";
import { ApolloProvider } from "react-apollo";
import withReduxStore from "../lib/with-redux-store";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { initializeStore } from "../store";
const { persistor } = initializeStore();
class MyApp extends App {
render() {
const { Component, pageProps, apolloClient, reduxStore } = this.props;
return (
<Container>
<ApolloProvider client={apolloClient}>
<Provider store={reduxStore}>
<PersistGate loading={"loading...."} persistor={persistor}>
<Component {...pageProps} />
</PersistGate>
</Provider>
</ApolloProvider>
</Container>
);
}
}
export default withApolloClient(withReduxStore(MyApp));
16 link: new HttpLink({
17 uri: process.env.GRAPH_URI, // Server URL (must be absolute)
18 credentials: "same-origin" // Additional fetch()options like `credentials` or `headers`
19 }),
About
Next js 7.0.2 mix lib with-apollo, with-ant-less, with-redux, redux-persist