)
}
diff --git a/docs/advanced/Middleware.md b/docs/advanced/Middleware.md
index fe51ff6493..2d7611224f 100644
--- a/docs/advanced/Middleware.md
+++ b/docs/advanced/Middleware.md
@@ -161,16 +161,14 @@ function applyMiddlewareByMonkeypatching(store, middlewares) {
middlewares.reverse()
// Transform dispatch function with each middleware.
- middlewares.forEach(middleware =>
- store.dispatch = middleware(store)
- )
+ middlewares.forEach(middleware => (store.dispatch = middleware(store)))
}
```
We could use it to apply multiple middleware like this:
```js
-applyMiddlewareByMonkeypatching(store, [ logger, crashReporter ])
+applyMiddlewareByMonkeypatching(store, [logger, crashReporter])
```
However, it is still monkeypatching.
@@ -250,16 +248,11 @@ Instead of `applyMiddlewareByMonkeypatching()`, we could write `applyMiddleware(
```js
// Warning: Naïve implementation!
// That's *not* Redux API.
-
function applyMiddleware(store, middlewares) {
middlewares = middlewares.slice()
middlewares.reverse()
-
let dispatch = store.dispatch
- middlewares.forEach(middleware =>
- dispatch = middleware(store)(dispatch)
- )
-
+ middlewares.forEach(middleware => (dispatch = middleware(store)(dispatch)))
return Object.assign({}, store, { dispatch })
}
```
@@ -368,10 +361,7 @@ const timeoutScheduler = store => next => action => {
return next(action)
}
- let timeoutId = setTimeout(
- () => next(action),
- action.meta.delay
- )
+ let timeoutId = setTimeout(() => next(action), action.meta.delay)
return function cancel() {
clearTimeout(timeoutId)
@@ -467,10 +457,9 @@ const readyStatePromise = store => next => action => {
* `dispatch` will return the return value of the dispatched function.
*/
const thunk = store => next => action =>
- typeof action === 'function' ?
- action(store.dispatch, store.getState) :
- next(action)
-
+ (typeof action === 'function'
+ ? action(store.dispatch, store.getState)
+ : next(action))
// You can use all of them! (It doesn't mean you should.)
let todoApp = combineReducers(reducers)
diff --git a/docs/advanced/UsageWithReactRouter.md b/docs/advanced/UsageWithReactRouter.md
index 692d2681c4..9923b82264 100644
--- a/docs/advanced/UsageWithReactRouter.md
+++ b/docs/advanced/UsageWithReactRouter.md
@@ -17,19 +17,19 @@ Before integrating React Router, we need to configure our development server. In
### Configuring Express
If you are serving your `index.html` from Express:
-``` js
- app.get('/*', (req,res) => {
- res.sendFile(path.join(__dirname, 'index.html'))
- })
+```js
+app.get('/*', (req, res) => {
+ res.sendFile(path.join(__dirname, 'index.html'))
+})
```
### Configuring WebpackDevServer
If you are serving your `index.html` from WebpackDevServer:
You can add to your webpack.config.dev.js:
```js
- devServer: {
- historyApiFallback: true,
- }
+devServer: {
+ historyApiFallback: true
+}
```
## Connecting React Router with Redux App
@@ -39,7 +39,7 @@ Along this chapter, we will be using the [Todos](https://github.com/reactjs/redu
First we will need to import `` and `` from React Router. Here's how to do it:
```js
-import { Router, Route } from 'react-router';
+import { Router, Route } from 'react-router'
```
In a React app, usually you would wrap `` in `` so that when the URL changes, `` will match a branch of its routes, and render their configured components. `` is used to declaratively map routes to your application's component hierarchy. You would declare in `path` the path used in the URL and in `component` the single component to be rendered when the route matches the URL.
@@ -48,8 +48,8 @@ In a React app, usually you would wrap `` in `` so that when
const Root = () => (
-
-);
+
+)
```
However, in our Redux App we will still need ``. `` is the higher-order component provided by React Redux that lets you bind Redux to React (see [Usage with React](../basics/UsageWithReact.md)).
@@ -57,7 +57,7 @@ However, in our Redux App we will still need ``. `` is t
We will then import the `` from React Redux:
```js
-import { Provider } from 'react-redux';
+import { Provider } from 'react-redux'
```
We will wrap `` in `` so that route handlers can get [access to the `store`](http://redux.js.org/docs/basics/UsageWithReact.html#passing-the-store).
@@ -69,7 +69,7 @@ const Root = ({ store }) => (
-);
+)
```
Now the `` component will be rendered if the URL matches '/'. Additionally, we will add the optional `(:filter)` parameter to `/`, because we will need it further on when we try to read the parameter `(:filter)` from the URL.
@@ -81,26 +81,26 @@ Now the `` component will be rendered if the URL matches '/'. Additionall
You will probably want to remove the hash from the URL (e.g: `http://localhost:3000/#/?_k=4sbb0i`). For doing this, you will need to also import `browserHistory` from React Router:
```js
-import { Router, Route, browserHistory } from 'react-router';
+import { Router, Route, browserHistory } from 'react-router'
```
and pass it to the `` in order to remove the hash from the URL:
```js
-
-
-
+
+
+
```
Unless you are targeting old browsers like IE9, you can always use `browserHistory`.
#### `components/Root.js`
-``` js
-import React from 'react';
-import PropTypes from 'prop-types';
-import { Provider } from 'react-redux';
-import { Router, Route, browserHistory } from 'react-router';
-import App from './App';
+```js
+import React from 'react'
+import PropTypes from 'prop-types'
+import { Provider } from 'react-redux'
+import { Router, Route, browserHistory } from 'react-router'
+import App from './App'
const Root = ({ store }) => (
@@ -108,20 +108,20 @@ const Root = ({ store }) => (
-);
+)
Root.propTypes = {
- store: PropTypes.object.isRequired,
-};
+ store: PropTypes.object.isRequired
+}
-export default Root;
+export default Root
```
We will also need to refactor `index.js` to render the `` component to the DOM.
#### `index.js`
```js
-import React from 'react';
+import React from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import todoApp from './reducers'
@@ -129,10 +129,7 @@ import Root from './components/Root'
let store = createStore(todoApp)
-render(
- ,
- document.getElementById('root')
-)
+render(, document.getElementById('root'))
```
## Navigating with React Router
@@ -142,8 +139,8 @@ React Router comes with a [``](https://github.com/ReactTraining/react-ro
#### `containers/FilterLink.js`
```js
-import React from 'react';
-import { Link } from 'react-router';
+import React from 'react'
+import { Link } from 'react-router'
const FilterLink = ({ filter, children }) => (
(
>
{children}
-);
+)
-export default FilterLink;
+export default FilterLink
```
#### `components/Footer.js`
@@ -166,22 +163,22 @@ import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
-
+)
export default Footer
```
@@ -196,8 +193,8 @@ Currently, the todo list is not filtered even after the URL changed. This is bec
const mapStateToProps = (state, ownProps) => {
return {
todos: getVisibleTodos(state.todos, ownProps.filter) // previously was getVisibleTodos(state.todos, state.visibilityFilter)
- };
-};
+ }
+}
```
Right now we are not passing anything to `` so `ownProps` is an empty object. To filter our todos according to the URL, we want to pass the URL params to ``.
@@ -214,13 +211,11 @@ const App = ({ params }) => {
return (
-
+
- );
-};
+ )
+}
```
## Next Steps
diff --git a/docs/api/Store.md b/docs/api/Store.md
index 661996d290..90edd69691 100644
--- a/docs/api/Store.md
+++ b/docs/api/Store.md
@@ -63,7 +63,7 @@ To learn how to describe asynchronous API calls, read the current state inside a
```js
import { createStore } from 'redux'
-let store = createStore(todos, [ 'Use Redux' ])
+let store = createStore(todos, ['Use Redux'])
function addTodo(text) {
return {
@@ -113,9 +113,14 @@ let currentValue
function handleChange() {
let previousValue = currentValue
currentValue = select(store.getState())
-
+
if (previousValue !== currentValue) {
- console.log('Some deep nested property changed from', previousValue, 'to', currentValue)
+ console.log(
+ 'Some deep nested property changed from',
+ previousValue,
+ 'to',
+ currentValue
+ )
}
}
diff --git a/docs/api/applyMiddleware.md b/docs/api/applyMiddleware.md
index 8e969bcbdd..34e9ac8afe 100644
--- a/docs/api/applyMiddleware.md
+++ b/docs/api/applyMiddleware.md
@@ -23,7 +23,7 @@ import { createStore, applyMiddleware } from 'redux'
import todos from './reducers'
function logger({ getState }) {
- return (next) => (action) => {
+ return next => action => {
console.log('will dispatch', action)
// Call the next dispatch method in the middleware chain.
@@ -37,11 +37,7 @@ function logger({ getState }) {
}
}
-let store = createStore(
- todos,
- [ 'Use Redux' ],
- applyMiddleware(logger)
-)
+let store = createStore(todos, ['Use Redux'], applyMiddleware(logger))
store.dispatch({
type: 'ADD_TODO',
@@ -70,7 +66,6 @@ function fetchSecretSauce() {
// These are the normal action creators you have seen so far.
// The actions they return can be dispatched without any middleware.
// However, they only express “facts” and not the “async flow”.
-
function makeASandwich(forPerson, secretSauce) {
return {
type: 'MAKE_SANDWICH',
@@ -78,7 +73,6 @@ function makeASandwich(forPerson, secretSauce) {
secretSauce
}
}
-
function apologize(fromPerson, toPerson, error) {
return {
type: 'APOLOGIZE',
@@ -87,131 +81,74 @@ function apologize(fromPerson, toPerson, error) {
error
}
}
-
function withdrawMoney(amount) {
return {
type: 'WITHDRAW',
amount
}
-}
-
-// Even without middleware, you can dispatch an action:
-store.dispatch(withdrawMoney(100))
-
-// But what do you do when you need to start an asynchronous action,
-// such as an API call, or a router transition?
-
-// Meet thunks.
-// A thunk is a function that returns a function.
-// This is a thunk.
-
+} // Even without middleware, you can dispatch an action:
+store.dispatch(withdrawMoney(100)) // But what do you do when you need to start an asynchronous action, // such as an API call, or a router transition? // Meet thunks. // A thunk is a function that returns a function. // This is a thunk.
function makeASandwichWithSecretSauce(forPerson) {
-
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
-
- return function (dispatch) {
+ return function(dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
)
}
-}
-
-// Thunk middleware lets me dispatch thunk async actions
-// as if they were actions!
-
-store.dispatch(
- makeASandwichWithSecretSauce('Me')
-)
-
-// It even takes care to return the thunk's return value
-// from the dispatch, so I can chain Promises as long as I return them.
-
-store.dispatch(
- makeASandwichWithSecretSauce('My wife')
-).then(() => {
+} // Thunk middleware lets me dispatch thunk async actions // as if they were actions!
+store.dispatch(makeASandwichWithSecretSauce('Me')) // It even takes care to return the thunk's return value // from the dispatch, so I can chain Promises as long as I return them.
+store.dispatch(makeASandwichWithSecretSauce('My wife')).then(() => {
console.log('Done!')
-})
-
-// In fact I can write action creators that dispatch
-// actions and async actions from other action creators,
-// and I can build my control flow with Promises.
-
+}) // In fact I can write action creators that dispatch // actions and async actions from other action creators, // and I can build my control flow with Promises.
function makeSandwichesForEverybody() {
- return function (dispatch, getState) {
+ return function(dispatch, getState) {
if (!getState().sandwiches.isShopOpen) {
-
// You don't have to return Promises, but it's a handy convention
// so the caller can always call .then() on async dispatch result.
-
return Promise.resolve()
- }
-
- // We can dispatch both plain object actions and other thunks,
- // which lets us compose the asynchronous actions in a single flow.
-
- return dispatch(
- makeASandwichWithSecretSauce('My Grandma')
- ).then(() =>
- Promise.all([
- dispatch(makeASandwichWithSecretSauce('Me')),
- dispatch(makeASandwichWithSecretSauce('My wife'))
- ])
- ).then(() =>
- dispatch(makeASandwichWithSecretSauce('Our kids'))
- ).then(() =>
- dispatch(getState().myMoney > 42 ?
- withdrawMoney(42) :
- apologize('Me', 'The Sandwich Shop')
+ } // We can dispatch both plain object actions and other thunks, // which lets us compose the asynchronous actions in a single flow.
+ return dispatch(makeASandwichWithSecretSauce('My Grandma'))
+ .then(() =>
+ Promise.all([
+ dispatch(makeASandwichWithSecretSauce('Me')),
+ dispatch(makeASandwichWithSecretSauce('My wife'))
+ ])
+ )
+ .then(() => dispatch(makeASandwichWithSecretSauce('Our kids')))
+ .then(() =>
+ dispatch(
+ getState().myMoney > 42
+ ? withdrawMoney(42)
+ : apologize('Me', 'The Sandwich Shop')
+ )
)
- )
}
-}
-
-// This is very useful for server side rendering, because I can wait
-// until data is available, then synchronously render the app.
-
+} // This is very useful for server side rendering, because I can wait // until data is available, then synchronously render the app.
import { renderToString } from 'react-dom/server'
-
-store.dispatch(
- makeSandwichesForEverybody()
-).then(() =>
- response.send(renderToString())
-)
-
-// I can also dispatch a thunk async action from a component
-// any time its props change to load the missing data.
-
+store
+ .dispatch(makeSandwichesForEverybody())
+ .then(() => response.send(renderToString())) // I can also dispatch a thunk async action from a component // any time its props change to load the missing data.
import { connect } from 'react-redux'
import { Component } from 'react'
-
class SandwichShop extends Component {
componentDidMount() {
- this.props.dispatch(
- makeASandwichWithSecretSauce(this.props.forPerson)
- )
+ this.props.dispatch(makeASandwichWithSecretSauce(this.props.forPerson))
}
-
componentWillReceiveProps(nextProps) {
if (nextProps.forPerson !== this.props.forPerson) {
- this.props.dispatch(
- makeASandwichWithSecretSauce(nextProps.forPerson)
- )
+ this.props.dispatch(makeASandwichWithSecretSauce(nextProps.forPerson))
}
}
-
render() {
return
{this.props.sandwiches.join('mustard')}
}
}
-
-export default connect(
- state => ({
- sandwiches: state.sandwiches
- })
-)(SandwichShop)
+export default connect(state => ({
+ sandwiches: state.sandwiches
+}))(SandwichShop)
```
#### Tips
@@ -223,19 +160,19 @@ export default connect(
* If you want to conditionally apply a middleware, make sure to only import it when it's needed:
```js
- let middleware = [ a, b ]
- if (process.env.NODE_ENV !== 'production') {
- let c = require('some-debug-middleware')
- let d = require('another-debug-middleware')
- middleware = [ ...middleware, c, d ]
- }
+let middleware = [a, b]
+if (process.env.NODE_ENV !== 'production') {
+ let c = require('some-debug-middleware')
+ let d = require('another-debug-middleware')
+ middleware = [...middleware, c, d]
+}
- const store = createStore(
- reducer,
- preloadedState,
- applyMiddleware(...middleware)
- )
- ```
+const store = createStore(
+ reducer,
+ preloadedState,
+ applyMiddleware(...middleware)
+)
+```
This makes it easier for bundling tools to cut out unneeded modules and reduces the size of your builds.
diff --git a/docs/api/bindActionCreators.md b/docs/api/bindActionCreators.md
index 68d7bf74ed..3c1bcc69c9 100644
--- a/docs/api/bindActionCreators.md
+++ b/docs/api/bindActionCreators.md
@@ -82,10 +82,7 @@ class TodoListContainer extends Component {
// removeTodo: Function
// }
- return (
-
- )
+ return
// An alternative to bindActionCreators is to pass
// just the dispatch function down, but then your child component
@@ -95,9 +92,7 @@ class TodoListContainer extends Component {
}
}
-export default connect(
- state => ({ todos: state.todos })
-)(TodoListContainer)
+export default connect(state => ({ todos: state.todos }))(TodoListContainer)
```
#### Tips
diff --git a/docs/api/combineReducers.md b/docs/api/combineReducers.md
index a126c43c67..ba1d8b938f 100644
--- a/docs/api/combineReducers.md
+++ b/docs/api/combineReducers.md
@@ -55,7 +55,7 @@ While `combineReducers` attempts to check that your reducers conform to some of
export default function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
- return state.concat([ action.text ])
+ return state.concat([action.text])
default:
return state
}
diff --git a/docs/api/compose.md b/docs/api/compose.md
index 887de902d0..4adbc23ffb 100644
--- a/docs/api/compose.md
+++ b/docs/api/compose.md
@@ -25,10 +25,7 @@ import reducer from '../reducers/index'
const store = createStore(
reducer,
- compose(
- applyMiddleware(thunk),
- DevTools.instrument()
- )
+ compose(applyMiddleware(thunk), DevTools.instrument())
)
```
diff --git a/docs/api/createStore.md b/docs/api/createStore.md
index 8ccdec7d13..f97a0a1266 100644
--- a/docs/api/createStore.md
+++ b/docs/api/createStore.md
@@ -23,13 +23,13 @@ import { createStore } from 'redux'
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
- return state.concat([ action.text ])
+ return state.concat([action.text])
default:
return state
}
}
-let store = createStore(todos, [ 'Use Redux' ])
+let store = createStore(todos, ['Use Redux'])
store.dispatch({
type: 'ADD_TODO',
diff --git a/docs/basics/Actions.md b/docs/basics/Actions.md
index 0446a36bcf..13b7040965 100644
--- a/docs/basics/Actions.md
+++ b/docs/basics/Actions.md
@@ -89,8 +89,8 @@ dispatch(completeTodo(index))
Alternatively, you can create a **bound action creator** that automatically dispatches:
```js
-const boundAddTodo = (text) => dispatch(addTodo(text))
-const boundCompleteTodo = (index) => dispatch(completeTodo(index))
+const boundAddTodo = text => dispatch(addTodo(text))
+const boundCompleteTodo = index => dispatch(completeTodo(index))
```
Now you'll be able to call them directly:
diff --git a/docs/basics/DataFlow.md b/docs/basics/DataFlow.md
index 00d07f205f..e5b1362318 100644
--- a/docs/basics/DataFlow.md
+++ b/docs/basics/DataFlow.md
@@ -27,26 +27,26 @@ The data lifecycle in any Redux app follows these 4 steps:
The [store](Store.md) will pass two arguments to the [reducer](Reducers.md): the current state tree and the action. For example, in the todo app, the root reducer might receive something like this:
```js
- // The current application state (list of todos and chosen filter)
- let previousState = {
- visibleTodoFilter: 'SHOW_ALL',
- todos: [
- {
- text: 'Read the docs.',
- complete: false
- }
- ]
+// The current application state (list of todos and chosen filter)
+let previousState = {
+ visibleTodoFilter: 'SHOW_ALL',
+ todos: [
+ {
+ text: 'Read the docs.',
+ complete: false
}
+ ]
+}
- // The action being performed (adding a todo)
- let action = {
- type: 'ADD_TODO',
- text: 'Understand the flow.'
- }
+// The action being performed (adding a todo)
+let action = {
+ type: 'ADD_TODO',
+ text: 'Understand the flow.'
+}
- // Your reducer returns the next application state
- let nextState = todoApp(previousState, action)
- ```
+// Your reducer returns the next application state
+let nextState = todoApp(previousState, action)
+```
Note that a reducer is a pure function. It only *computes* the next state. It should be completely predictable: calling it with the same inputs many times should produce the same outputs. It shouldn't perform any side effects like API calls or router transitions. These should happen before an action is dispatched.
@@ -57,28 +57,28 @@ The data lifecycle in any Redux app follows these 4 steps:
Here's how [`combineReducers()`](../api/combineReducers.md) works. Let's say you have two reducers, one for a list of todos, and another for the currently selected filter setting:
```js
- function todos(state = [], action) {
- // Somehow calculate it...
- return nextState
- }
-
- function visibleTodoFilter(state = 'SHOW_ALL', action) {
- // Somehow calculate it...
- return nextState
- }
-
- let todoApp = combineReducers({
- todos,
- visibleTodoFilter
- })
- ```
+function todos(state = [], action) {
+ // Somehow calculate it...
+ return nextState
+}
+
+function visibleTodoFilter(state = 'SHOW_ALL', action) {
+ // Somehow calculate it...
+ return nextState
+}
+
+let todoApp = combineReducers({
+ todos,
+ visibleTodoFilter
+})
+```
When you emit an action, `todoApp` returned by `combineReducers` will call both reducers:
```js
- let nextTodos = todos(state.todos, action)
- let nextVisibleTodoFilter = visibleTodoFilter(state.visibleTodoFilter, action)
- ```
+let nextTodos = todos(state.todos, action)
+let nextVisibleTodoFilter = visibleTodoFilter(state.visibleTodoFilter, action)
+```
It will then combine both sets of results into a single state tree:
diff --git a/docs/basics/ExampleTodoList.md b/docs/basics/ExampleTodoList.md
index ea81a095c5..ad3430589e 100644
--- a/docs/basics/ExampleTodoList.md
+++ b/docs/basics/ExampleTodoList.md
@@ -30,7 +30,7 @@ render(
```js
let nextTodoId = 0
-export const addTodo = (text) => {
+export const addTodo = text => {
return {
type: 'ADD_TODO',
id: nextTodoId++,
@@ -38,14 +38,14 @@ export const addTodo = (text) => {
}
}
-export const setVisibilityFilter = (filter) => {
+export const setVisibilityFilter = filter => {
return {
type: 'SET_VISIBILITY_FILTER',
filter
}
}
-export const toggleTodo = (id) => {
+export const toggleTodo = id => {
return {
type: 'TOGGLE_TODO',
id
@@ -74,7 +74,7 @@ const todo = (state = {}, action) => {
return Object.assign({}, state, {
completed: !state.completed
})
-
+
default:
return state
}
@@ -83,14 +83,9 @@ const todo = (state = {}, action) => {
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
- return [
- ...state,
- todo(undefined, action)
- ]
+ return [...state, todo(undefined, action)]
case 'TOGGLE_TODO':
- return state.map(t =>
- todo(t, action)
- )
+ return state.map(t => todo(t, action))
default:
return state
}
@@ -134,7 +129,7 @@ export default todoApp
#### `components/Todo.js`
```js
-import React, from 'react'
+import React from 'react'
import PropTypes from 'prop-types'
const Todo = ({ onClick, completed, text }) => (
@@ -166,22 +161,20 @@ import Todo from './Todo'
const TodoList = ({ todos, onTodoClick }) => (