mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
extendable with-redux example (#3947)
* copied with-redux -> with-redux-wrapper, changed links in readme * added simplified redux wrapper * removed next-redux-wrapper dep * changed imports to local wrapper * changed readme to reflect changes
This commit is contained in:
parent
edfd44c3ca
commit
359e25af13
60
examples/with-redux-wrapper/README.md
Normal file
60
examples/with-redux-wrapper/README.md
Normal file
|
@ -0,0 +1,60 @@
|
|||
[![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-redux-wrapper)
|
||||
|
||||
# Redux example
|
||||
|
||||
## How to use
|
||||
|
||||
### Using `create-next-app`
|
||||
|
||||
Download [`create-next-app`](https://github.com/segmentio/create-next-app) to bootstrap the example:
|
||||
|
||||
```
|
||||
npm i -g create-next-app
|
||||
create-next-app --example with-redux-wrapper with-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-redux-wrapper
|
||||
cd with-redux-wrapper
|
||||
```
|
||||
|
||||
Install it and run:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run 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`
|
35
examples/with-redux-wrapper/components/AddCount.js
Normal file
35
examples/with-redux-wrapper/components/AddCount.js
Normal file
|
@ -0,0 +1,35 @@
|
|||
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 = ({ count }) => ({ count })
|
||||
|
||||
const mapDispatchToProps = (dispatch) => {
|
||||
return {
|
||||
addCount: bindActionCreators(addCount, dispatch)
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(AddCount)
|
24
examples/with-redux-wrapper/components/Clock.js
Normal file
24
examples/with-redux-wrapper/components/Clock.js
Normal 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
|
17
examples/with-redux-wrapper/components/Page.js
Normal file
17
examples/with-redux-wrapper/components/Page.js
Normal file
|
@ -0,0 +1,17 @@
|
|||
import Link from 'next/link'
|
||||
import { connect } from 'react-redux'
|
||||
import Clock from './Clock'
|
||||
import AddCount from './AddCount'
|
||||
|
||||
export default connect(state => state)(({ 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>
|
||||
)
|
||||
})
|
20
examples/with-redux-wrapper/package.json
Normal file
20
examples/with-redux-wrapper/package.json
Normal file
|
@ -0,0 +1,20 @@
|
|||
{
|
||||
"name": "with-redux-wrapper",
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"dev": "next",
|
||||
"build": "next build",
|
||||
"start": "next start"
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "latest",
|
||||
"next-redux-wrapper": "^1.0.0",
|
||||
"react": "^16.0.0",
|
||||
"redux-devtools-extension": "^2.13.2",
|
||||
"react-dom": "^16.0.0",
|
||||
"react-redux": "^5.0.1",
|
||||
"redux": "^3.6.0",
|
||||
"redux-thunk": "^2.1.0"
|
||||
},
|
||||
"license": "ISC"
|
||||
}
|
37
examples/with-redux-wrapper/pages/index.js
Normal file
37
examples/with-redux-wrapper/pages/index.js
Normal file
|
@ -0,0 +1,37 @@
|
|||
import React from 'react'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { initStore, startClock, addCount, serverRenderClock } from '../store'
|
||||
import withRedux from 'next-redux-wrapper'
|
||||
import Page from '../components/Page'
|
||||
|
||||
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 withRedux(initStore, null, mapDispatchToProps)(Counter)
|
36
examples/with-redux-wrapper/pages/other.js
Normal file
36
examples/with-redux-wrapper/pages/other.js
Normal file
|
@ -0,0 +1,36 @@
|
|||
import React from 'react'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { initStore, startClock, addCount, serverRenderClock } from '../store'
|
||||
import withRedux from 'next-redux-wrapper'
|
||||
import Page from '../components/Page'
|
||||
|
||||
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 withRedux(initStore, null, mapDispatchToProps)(Counter)
|
44
examples/with-redux-wrapper/store.js
Normal file
44
examples/with-redux-wrapper/store.js
Normal file
|
@ -0,0 +1,44 @@
|
|||
import { createStore, applyMiddleware } from 'redux'
|
||||
import { composeWithDevTools } from 'redux-devtools-extension'
|
||||
import thunkMiddleware from 'redux-thunk'
|
||||
|
||||
const exampleInitialState = {
|
||||
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 Object.assign({}, state, { lastUpdate: action.ts, light: !!action.light })
|
||||
case actionTypes.ADD:
|
||||
return Object.assign({}, state, {
|
||||
count: state.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 initStore = (initialState = exampleInitialState) => {
|
||||
return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunkMiddleware)))
|
||||
}
|
|
@ -37,17 +37,21 @@ now
|
|||
|
||||
## The idea behind the example
|
||||
|
||||
This example is based on [full example](https://github.com/kirill-konshin/next-redux-wrapper) which should probably be used for production. The next.js example with this library can be found [here](https://github.com/zeit/next.js/tree/canary/examples/with-redux-wrapper)
|
||||
|
||||
The reason for this example is to show an easier to follow and extendable way to include Redux in a next.js app.
|
||||
|
||||
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.
|
||||
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 `withRedux.js`, 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.
|
||||
`withRedux` function accepts `initStore` as first argument, all other arguments are internally passed to `react-redux connect()` function. `initStore` function will receive initialState as one argument and should return a new instance of redux store each time when called, no memoization needed here.
|
||||
|
||||
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.
|
||||
|
||||
|
|
|
@ -8,7 +8,6 @@
|
|||
},
|
||||
"dependencies": {
|
||||
"next": "latest",
|
||||
"next-redux-wrapper": "^1.0.0",
|
||||
"react": "^16.0.0",
|
||||
"redux-devtools-extension": "^2.13.2",
|
||||
"react-dom": "^16.0.0",
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import React from 'react'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { initStore, startClock, addCount, serverRenderClock } from '../store'
|
||||
import withRedux from 'next-redux-wrapper'
|
||||
import withRedux from '../utils/withRedux'
|
||||
import Page from '../components/Page'
|
||||
|
||||
class Counter extends React.Component {
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import React from 'react'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { initStore, startClock, addCount, serverRenderClock } from '../store'
|
||||
import withRedux from 'next-redux-wrapper'
|
||||
import withRedux from '../utils/withRedux'
|
||||
import Page from '../components/Page'
|
||||
|
||||
class Counter extends React.Component {
|
||||
|
|
58
examples/with-redux/utils/withRedux.js
Normal file
58
examples/with-redux/utils/withRedux.js
Normal file
|
@ -0,0 +1,58 @@
|
|||
import React from 'react'
|
||||
import { connect, Provider } from 'react-redux'
|
||||
|
||||
const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__'
|
||||
|
||||
// https://github.com/iliakan/detect-node
|
||||
const checkServer = () => Object.prototype.toString.call(global.process) === '[object process]'
|
||||
|
||||
const getOrCreateStore = (initStore, initialState) => {
|
||||
// Always make a new store if server
|
||||
if (checkServer() || typeof window === 'undefined') {
|
||||
return initStore(initialState)
|
||||
}
|
||||
|
||||
// Store in global variable if client
|
||||
if (!window[__NEXT_REDUX_STORE__]) {
|
||||
window[__NEXT_REDUX_STORE__] = initStore(initialState)
|
||||
}
|
||||
return window[__NEXT_REDUX_STORE__]
|
||||
}
|
||||
|
||||
export default (...args) => (Component) => {
|
||||
// First argument is initStore, the rest are redux connect arguments and get passed
|
||||
const [initStore, ...connectArgs] = args
|
||||
|
||||
const ComponentWithRedux = (props = {}) => {
|
||||
const { store, initialProps, initialState } = props
|
||||
|
||||
// Connect page to redux with connect arguments
|
||||
const ConnectedComponent = connect.apply(null, connectArgs)(Component)
|
||||
|
||||
// Wrap with redux Provider with store
|
||||
// Create connected page with initialProps
|
||||
return React.createElement(
|
||||
Provider,
|
||||
{ store: store && store.dispatch ? store : getOrCreateStore(initStore, initialState) },
|
||||
React.createElement(ConnectedComponent, initialProps)
|
||||
)
|
||||
}
|
||||
|
||||
ComponentWithRedux.getInitialProps = async (props = {}) => {
|
||||
const isServer = checkServer()
|
||||
const store = getOrCreateStore(initStore)
|
||||
|
||||
// Run page getInitialProps with store and isServer
|
||||
const initialProps = Component.getInitialProps
|
||||
? await Component.getInitialProps({ ...props, isServer, store })
|
||||
: {}
|
||||
|
||||
return {
|
||||
store,
|
||||
initialState: store.getState(),
|
||||
initialProps
|
||||
}
|
||||
}
|
||||
|
||||
return ComponentWithRedux
|
||||
}
|
Loading…
Reference in a new issue