@pimred/redux
v0.2.5
Published
Redux setup usable by NextJS apps
Downloads
44
Readme
@pimred/redux
Redux setup usable by NextJS apps
Installation
npm install --save @pimred/redux
Usage
Connect your NextJS app with redux.
(It's using next-redux-wrapper behind the scenes).
pages/_app.js
import { reduxWrapper } from '@pimred/redux'
const MyApp = ({ Component, pageProps }) => {
return <Component {...pageProps} />
}
MyApp.propTypes = {
Component : PropTypes.func.isRequired,
pageProps : PropTypes.object.isRequired
}
export default reduxWrapper.withRedux(MyApp)
The reducers can be lazy loaded.
This example used the structure of Redux ducks.
modules/anyModule.js
import { reducerRegistry } from '@pimred/redux'
const reducerName = '...'
reducerRegistry.register(reducerName, reducer)
You can use getServerSideProps or getStaticProps in any page.
pages/anyPage.js
import { reduxWrapper } from '@pimred/redux'
const AnyPage = () => { ... }
export const getServerSideProps = reduxWrapper.getServerSideProps(async ({ store }) => {
// do anything with store like: await store.dispatch(...)
})
State hydration
Each time when pages that have getServerSideProps are opened by user the HYDRATE action will be dispatched. The payload of this action will contain the state at the moment of server side rendering, it will not have client state. If you need to preserve data in the client state, you can use SURVIVE_HYDRATION as name for the key in a reducer. This data will be preserved in the state after hydration.
import { SURVIVE_HYDRATION } from '@pimred/redux'
// Reducer
export function reducer (state = initialState, action = {}) {
switch (action.type) {
case ANY_ACTION: {
return {
...state,
[SURVIVE_HYDRATION]: {
data: 'This data is set by the client and survives hydration'
}
}
}
}
return state
}
SURVIVE_HYDRATION must be set in the first level in der reducer data.
import { SURVIVE_HYDRATION } from '@pimred/redux'
const initialState = {
someOtherData: 'will be filled by server side rendering and overwrite client state',
// Don't add SURVIVE_HYDRATION to the initial state
// But it must be in this level
}
// Reducer
export function reducer (state = initialState, action = {}) {
switch (action.type) {
case ANY_ACTION: {
return {
...state,
[SURVIVE_HYDRATION]: {
data: 'This data is set by the client and survives hydration'
}
}
}
}
return state
}