Next.js: state from getInitialProps Redux

Created on 9 May 2017  路  1Comment  路  Source: vercel/next.js

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:

  1. Why is getiInitialProps only useful using the Link component?
  2. Should I repeat the store.dispatch in the componentWillMount also to get the same results when accessing the url, is it the best strategy?
  3. What strategy would recommend that, when updating the page in the browser does not reboot the store?

>All comments

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
}

:/

Was this page helpful?
0 / 5 - 0 ratings

Related issues

olifante picture olifante  路  3Comments

DvirSh picture DvirSh  路  3Comments

jesselee34 picture jesselee34  路  3Comments

knipferrc picture knipferrc  路  3Comments

formula349 picture formula349  路  3Comments