open-index/open-npm huggingface dataset:
npm package: @pimred/redux
Description: Redux setup usable by NextJS apps
Latest version: 0.2.5

# @pimred/redux

> Redux setup usable by NextJS apps

[![NPM](https://img.shields.io/npm/v/@pimred/redux.svg)](https://www.npmjs.com/package/@pimred/redux) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)

## Installation

```bash
npm install --save @pimred/redux
```

## Usage

Connect your NextJS app with redux.\
(It's using [next-redux-wrapper](https://github.com/kirill-konshin/next-redux-wrapper) behind the scenes).

**pages/_app.js**

```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](https://github.com/erikras/ducks-modular-redux).

**modules/anyModule.js**
```js
import { reducerRegistry } from '@pimred/redux'

const reducerName = '...'
reducerRegistry.register(reducerName, reducer)
```
You can use **getServerSideProps** or **getStaticProps** in any page.

**pages/anyPage.js**

```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.

```js
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.

```js
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
}
```