I have managed to maintain redux state throughout my application by injecting the state from the getInitialProps and using the withRedux wrapper for my pages. One of my pages look like this:
class Events extends React.Component {
static async getInitialProps({ store, req, query }) {
const isServer = !!req;
store.dispatch(event.eventFetchData(https://myapi.com/v1/events/url=${query.name}));
return { initialState: store.getState(), isServer};
}
constructor(props) {
super(props);
this.store = initStore(props.initialState);
}
render () {
return (
<Provider store={this.store}>
<Layout title='Events'>
<div>Events</div>
<Event/>
</Layout>
</Provider>
)
}
}
export default withRedux(initStore)(Events);
This is how my store looks:
import { createStore, applyMiddleware, compose} from 'redux';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger'
import rootReducer from '../reducers'; // <-- This is a combined reducer
const composeEnhancers = typeof window !== 'undefined' &&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const loggerMiddleware = createLogger()
const createStoreWithMiddleware = composeEnhancers(applyMiddleware(thunkMiddleware, loggerMiddleware));
let reduxStore = null
export const initStore = (client, initialState) => {
let store
if (!process.browser || !reduxStore) {
store = createStore( rootReducer, createStoreWithMiddleware )
if (!process.browser) {
return store
}
reduxStore = store
}
return reduxStore
}
This works fine when i access to the page by the Link component, as the documentation says:
'For the initial page load, getInitialProps will execute on the server only. getInitialProps will only be executed on the client when navigating to a different route via the Link component or using the routing APIs'
But I have some questions about this:
Update:
I wasn`t passing the initialState to my store
export const initStore = (initialState) => {
let store
if (!process.browser || !reduxStore) {
store = createStore( rootReducer, initialState, createStoreWithMiddleware )
if (!process.browser) {
return store
}
reduxStore = store
}
return reduxStore
}
:/