1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Add Example of Redux Wrapper with Immutable.js (#4327)

* Add immutable redux example

* Updated readme

* Fix linting errors
This commit is contained in:
Jason Leibowitz 2018-05-10 13:40:21 -04:00 committed by Tim Neutkens
parent d6ca2f89b8
commit 126507cc1c
9 changed files with 332 additions and 0 deletions

View file

@ -0,0 +1,76 @@
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-immutable-redux-wrapper)
# Immutable Redux Example
> This example and documentation is based on the [with-redux](https://github.com/zeit/next.js/tree/master/examples/with-redux) example.
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/segmentio/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npx create-next-app --example with-immutable-redux-wrapper with-immutable-redux-wrapper-app
# or
yarn create next-app --example with-immutable-redux-wrapper with-immutable-redux-wrapper-app
```
### Download manually
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-immutable-redux-wrapper
cd with-redux-wrapper
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
Usually splitting your app state into `pages` feels natural but sometimes you'll want to have global state for your app. This is an example on how you can use redux that also works with our universal rendering approach. This is just a way you can do it but it's not the only one.
In the first example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color than the client one.
![](http://i.imgur.com/JCxtWSj.gif)
Our page is located at `pages/index.js` so it will map the route `/`. To get the initial data for rendering we are implementing the static method `getInitialProps`, initializing the redux store and dispatching the required actions until we are ready to return the initial state to be rendered. Since the component is wrapped with `next-redux-wrapper`, the component is automatically connected to Redux and wrapped with `react-redux Provider`, that allows us to access redux state immediately and send the store down to children components so they can access to the state when required.
For safety it is recommended to wrap all pages, no matter if they use Redux or not, so that you should not care about it anymore in all child components.
`withRedux` function accepts `makeStore` as first argument, all other arguments are internally passed to `react-redux connect()` function. `makeStore` function will receive initialState as one argument and should return a new instance of redux store each time when called, no memoization needed here. See the [full example](https://github.com/kirill-konshin/next-redux-wrapper#usage) in the Next Redux Wrapper repository. And there's another package [next-connect-redux](https://github.com/huzidaha/next-connect-redux) available with similar features.
To pass the initial state from the server to the client we pass it as a prop called `initialState` so then it's available when the client takes over.
The trick here for supporting universal redux is to separate the cases for the client and the server. When we are on the server we want to create a new store every time, otherwise different users data will be mixed up. If we are in the client we want to use always the same store. That's what we accomplish on `store.js`
The clock, under `components/Clock.js`, has access to the state using the `connect` function from `react-redux`. In this case Clock is a direct child from the page but it could be deep down the render tree.
The second example, under `components/AddCount.js`, shows a simple add counter function with a class component implementing a common redux pattern of mapping state and props. Again, the first render is happening in the server and instead of starting the count at 0, it will dispatch an action in redux that starts the count at 1. This continues to highlight how each navigation triggers a server render first and then a client render second, when you navigate between pages.
For simplicity and readability, Reducers, Actions, and Store creators are all in the same file: `store.js`
## What changed with immutable-redux-wrapper
Immutability can bring increased performance to your app, and leads to simpler programming and debugging, as data that never changes is easier to reason about than data that is free to be changed arbitrarily throughout your app.
In fact, Redux requires your state to be immutable. You do not have to use Immutable.JS as regular JavaScript, when written correctly, is perfectly capable of providing immutability on its own. However, guaranteeing immutability with JavaScript is difficult, and it can be easy to mutate an object accidentally, causing both bugs in your app that are extremely difficult to locate. For this reason, using an immutable update library such as Immutable.JS can significantly improve the reliability of your app and make your app's development much easier.
[Read more](https://redux.js.org/faq/immutable-data#what-approaches-are-there-for-handling-data-immutability-do-i-have-to-use-immutable-js) about the importance of immutability in Redux here.
This example wraps the exiting with-redux-wrapper example in Immutable.JS and displays how to pass immutable data from state to components.

View file

@ -0,0 +1,36 @@
/* eslint-disable */
import React, {Component} from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { addCount } from '../store'
class AddCount extends Component {
add = () => {
this.props.addCount()
}
render () {
const { count } = this.props
return (
<div>
<style jsx>{`
div {
padding: 0 0 20px 0;
}
`}</style>
<h1>AddCount: <span>{count}</span></h1>
<button onClick={this.add}>Add To Count</button>
</div>
)
}
}
const mapStateToProps = (state => ({ count: state.get('count') }))
const mapDispatchToProps = (dispatch) => {
return {
addCount: bindActionCreators(addCount, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AddCount)

View file

@ -0,0 +1,24 @@
export default ({ lastUpdate, light }) => {
return (
<div className={light ? 'light' : ''}>
{format(new Date(lastUpdate))}
<style jsx>{`
div {
padding: 15px;
display: inline-block;
color: #82FA58;
font: 50px menlo, monaco, monospace;
background-color: #000;
}
.light {
background-color: #999;
}
`}</style>
</div>
)
}
const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
const pad = n => n < 10 ? `0${n}` : n

View file

@ -0,0 +1,20 @@
import Link from 'next/link'
import { connect } from 'react-redux'
import Clock from './Clock'
import AddCount from './AddCount'
export default connect(state => ({
lastUpdate: state.get('lastUpdate'),
light: state.get('light')
}))(({ title, linkTo, lastUpdate, light }) => {
return (
<div>
<h1>{title}</h1>
<Clock lastUpdate={lastUpdate} light={light} />
<AddCount />
<nav>
<Link href={linkTo}><a>Navigate</a></Link>
</nav>
</div>
)
})

View file

@ -0,0 +1,21 @@
{
"name": "with-redux-wrapper",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"immutable": "4.0.0-rc.9",
"next": "^6.0.0",
"next-redux-wrapper": "2.0.0-beta.6",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-redux": "^5.0.1",
"redux": "^3.6.0",
"redux-devtools-extension": "^2.13.2",
"redux-thunk": "^2.1.0"
},
"license": "ISC"
}

View file

@ -0,0 +1,32 @@
import React from 'react'
import { Provider } from 'react-redux'
import App, { Container } from 'next/app'
import withRedux from 'next-redux-wrapper'
import { makeStore } from '../store'
import { fromJS } from 'immutable'
class MyApp extends App {
static async getInitialProps ({ Component, ctx }) {
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {}
return { pageProps }
}
render () {
const { Component, pageProps, store } = this.props
return (
<Container>
<Provider store={store}>
<Component {...pageProps} />
</Provider>
</Container>
)
}
}
export default withRedux(makeStore, {
serializeState: state => state.toJS(),
deserializeState: state => fromJS(state)
})(MyApp)

View file

@ -0,0 +1,37 @@
import React from 'react'
import { bindActionCreators } from 'redux'
import { startClock, addCount, serverRenderClock } from '../store'
import Page from '../components/Page'
import { connect } from 'react-redux'
class Counter extends React.Component {
static getInitialProps ({ store, isServer }) {
store.dispatch(serverRenderClock(isServer))
store.dispatch(addCount())
return { isServer }
}
componentDidMount () {
this.timer = this.props.startClock()
}
componentWillUnmount () {
clearInterval(this.timer)
}
render () {
return (
<Page title='Index Page' linkTo='/other' />
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
addCount: bindActionCreators(addCount, dispatch),
startClock: bindActionCreators(startClock, dispatch)
}
}
export default connect(null, mapDispatchToProps)(Counter)

View file

@ -0,0 +1,36 @@
import React from 'react'
import { bindActionCreators } from 'redux'
import { startClock, addCount, serverRenderClock } from '../store'
import Page from '../components/Page'
import { connect } from 'react-redux'
class Counter extends React.Component {
static getInitialProps ({ store, isServer }) {
store.dispatch(serverRenderClock(isServer))
store.dispatch(addCount())
return { isServer }
}
componentDidMount () {
this.timer = this.props.startClock()
}
componentWillUnmount () {
clearInterval(this.timer)
}
render () {
return (
<Page title='Other Page' linkTo='/' />
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
addCount: bindActionCreators(addCount, dispatch),
startClock: bindActionCreators(startClock, dispatch)
}
}
export default connect(null, mapDispatchToProps)(Counter)

View file

@ -0,0 +1,50 @@
import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunkMiddleware from 'redux-thunk'
import { fromJS } from 'immutable'
const exampleInitialState = fromJS({
lastUpdate: 0,
light: false,
count: 0
})
export const actionTypes = {
ADD: 'ADD',
TICK: 'TICK'
}
// REDUCERS
export const reducer = (state = exampleInitialState, action) => {
switch (action.type) {
case actionTypes.TICK:
return state.merge({
lastUpdate: action.ts,
light: !!action.light
})
case actionTypes.ADD:
return state.merge({
count: state.get('count') + 1
})
default: return state
}
}
// ACTIONS
export const serverRenderClock = (isServer) => dispatch => {
return dispatch({ type: actionTypes.TICK, light: !isServer, ts: Date.now() })
}
export const startClock = () => dispatch => {
return setInterval(() => dispatch({ type: actionTypes.TICK, light: true, ts: Date.now() }), 1000)
}
export const addCount = () => dispatch => {
return dispatch({ type: actionTypes.ADD })
}
export const makeStore = (initialState = exampleInitialState) => {
return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunkMiddleware)))
}