Hi,
I'm trying to figure out how to adjust to the next.js paradigm.
Coming from react-router, you would have an index.js where you would wrap the router with a
Since there is no react-router single instance when using next.js, but instead you simply define the main containers in the 'pages' folder - how would you create the store in one place and reference it from all containers?
The redux example on the Next.js Wiki demonstrate a single counter component...
How would you tackle multiple pages needing to reference the same store?
Cheers
Ajar
My Apollo example: https://github.com/relatemind/relate shows one way to share a store between pages (kind of an evolution of the Redux example). You can declare a HOC referenced from every page, and which will take care of providing the store to child components. But I wonder if/how things could be improved now that https://github.com/zeit/next.js/pull/301 is available? Haven't looked into that yet. Also see ongoing discussion in https://github.com/zeit/next.js/issues/387.
You can also take the approach of a 'global' layout like described here: https://github.com/zeit/next.js/wiki/Global-styles-and-layouts
import React from 'react'
import Page from '../layouts/main'
export default () => (
<Page>
<p>my page with global styles!</p>
</Page>
)
That way you can have a shared 'Page' between all your pages, and put your central store in there.
Same can be reached with a HOC by returning your component wrapped in a function.
If you look at the store code in the redux example wiki page it actually puts the store on a global variable. If you transition to a new page and call initStore it just returns the existing one so the store is persisted across pages.
export const initStore = (reducer, initialState, isServer) => {
if (isServer && typeof window === 'undefined') {
return createStore(reducer, initialState, applyMiddleware(thunkMiddleware))
} else {
if (!window.store) {
window.store = createStore(reducer, initialState, applyMiddleware(thunkMiddleware))
}
return window.store
}
}
You just need to render a <Provider> at the root of each page and pass in that store.
Thanks a lot for the great examples @sedubois @jonaswindey @MarcoThePoro
I believe you can achieve that using Next.JS Links
Most helpful comment
If you look at the store code in the redux example wiki page it actually puts the store on a global variable. If you transition to a new page and call
initStoreit just returns the existing one so the store is persisted across pages.You just need to render a
<Provider>at the root of each page and pass in that store.