From ae0487ba9d0b9d993f5781faeb93645f0a1f0ee4 Mon Sep 17 00:00:00 2001
From: Mateusz Zatorski
Date: Thu, 31 Mar 2016 01:29:39 +0100
Subject: [PATCH 1/4] [WIP] refactor to eslint airbnb, remove babel-eslint
---
.eslintrc | 16 +-
build/es3ify.js | 25 -
build/use-lodash-es.js | 10 -
examples/async/actions/index.js | 46 +-
examples/async/components/Picker.js | 16 +-
examples/async/components/Posts.js | 8 +-
examples/async/containers/App.js | 78 +-
examples/async/index.js | 16 +-
examples/async/reducers/index.js | 38 +-
examples/async/store/configureStore.js | 18 +-
examples/buildAll.js | 32 +-
examples/counter/components/Counter.js | 22 +-
examples/counter/index.js | 22 +-
examples/counter/reducers/index.js | 6 +-
.../counter/test/components/Counter.spec.js | 80 +--
.../counter/test/reducers/counter.spec.js | 24 +-
examples/real-world/actions/index.js | 100 +--
examples/real-world/components/Explore.js | 33 +-
examples/real-world/components/List.js | 33 +-
examples/real-world/components/Repo.js | 20 +-
examples/real-world/components/User.js | 14 +-
examples/real-world/containers/App.js | 50 +-
examples/real-world/containers/DevTools.js | 13 +-
examples/real-world/containers/RepoPage.js | 79 ++-
examples/real-world/containers/Root.dev.js | 18 +-
examples/real-world/containers/Root.js | 4 +-
examples/real-world/containers/Root.prod.js | 16 +-
examples/real-world/containers/UserPage.js | 82 +--
examples/real-world/index.js | 20 +-
examples/real-world/middleware/api.js | 84 +--
examples/real-world/reducers/index.js | 40 +-
examples/real-world/reducers/paginate.js | 43 +-
examples/real-world/routes.js | 18 +-
.../real-world/store/configureStore.dev.js | 22 +-
examples/real-world/store/configureStore.js | 4 +-
.../real-world/store/configureStore.prod.js | 10 +-
examples/shopping-cart/actions/index.js | 36 +-
examples/shopping-cart/api/shop.js | 12 +-
examples/shopping-cart/components/Cart.js | 22 +-
examples/shopping-cart/components/Product.js | 10 +-
.../shopping-cart/components/ProductItem.js | 24 +-
.../shopping-cart/components/ProductsList.js | 8 +-
.../shopping-cart/constants/ActionTypes.js | 10 +-
examples/shopping-cart/containers/App.js | 12 +-
.../shopping-cart/containers/CartContainer.js | 33 +-
.../containers/ProductsContainer.js | 31 +-
examples/shopping-cart/index.js | 30 +-
examples/shopping-cart/reducers/cart.js | 37 +-
examples/shopping-cart/reducers/index.js | 16 +-
examples/shopping-cart/reducers/products.js | 39 +-
.../test/components/Cart.spec.js | 76 +-
.../test/components/Product.spec.js | 30 +-
.../test/components/ProductItem.spec.js | 78 +-
.../test/components/ProductsList.spec.js | 30 +-
.../shopping-cart/test/reducers/cart.spec.js | 48 +-
.../test/reducers/products.spec.js | 48 +-
.../test/reducers/selectors.spec.js | 66 +-
examples/testAll.js | 26 +-
examples/todomvc/actions/index.js | 14 +-
examples/todomvc/components/Footer.js | 44 +-
examples/todomvc/components/Header.js | 19 +-
examples/todomvc/components/MainSection.js | 68 +-
examples/todomvc/components/TodoItem.js | 64 +-
examples/todomvc/components/TodoTextInput.js | 40 +-
examples/todomvc/constants/ActionTypes.js | 12 +-
examples/todomvc/constants/TodoFilters.js | 6 +-
examples/todomvc/containers/App.js | 30 +-
examples/todomvc/index.js | 18 +-
examples/todomvc/reducers/index.js | 10 +-
examples/todomvc/reducers/todos.js | 42 +-
examples/todomvc/store/configureStore.js | 14 +-
examples/todomvc/test/actions/todos.spec.js | 44 +-
.../todomvc/test/components/Footer.spec.js | 128 ++--
.../todomvc/test/components/Header.spec.js | 66 +-
.../test/components/MainSection.spec.js | 164 ++---
.../todomvc/test/components/TodoItem.spec.js | 148 ++--
.../test/components/TodoTextInput.spec.js | 98 +--
examples/todomvc/test/reducers/todos.spec.js | 184 ++---
examples/todomvc/test/setup.js | 8 +-
examples/todos-with-undo/actions/index.js | 26 +-
examples/todos-with-undo/components/App.js | 14 +-
examples/todos-with-undo/components/Footer.js | 8 +-
examples/todos-with-undo/components/Link.js | 22 +-
examples/todos-with-undo/components/Todo.js | 12 +-
.../todos-with-undo/components/TodoList.js | 14 +-
.../todos-with-undo/containers/AddTodo.js | 47 +-
.../todos-with-undo/containers/FilterLink.js | 28 +-
.../todos-with-undo/containers/UndoRedo.js | 35 +-
.../containers/VisibleTodoList.js | 36 +-
examples/todos-with-undo/index.js | 20 +-
examples/todos-with-undo/reducers/index.js | 12 +-
examples/todos-with-undo/reducers/todos.js | 32 +-
.../reducers/visibilityFilter.js | 8 +-
examples/todos/actions/index.js | 26 +-
examples/todos/components/App.js | 12 +-
examples/todos/components/Footer.js | 8 +-
examples/todos/components/Link.js | 22 +-
examples/todos/components/Todo.js | 12 +-
examples/todos/components/TodoList.js | 14 +-
examples/todos/containers/AddTodo.js | 47 +-
examples/todos/containers/FilterLink.js | 28 +-
examples/todos/containers/VisibleTodoList.js | 36 +-
examples/todos/index.js | 18 +-
examples/todos/reducers/index.js | 12 +-
examples/todos/reducers/todos.js | 26 +-
examples/todos/reducers/visibilityFilter.js | 8 +-
examples/todos/test/actions/todos.spec.js | 24 +-
examples/todos/test/reducers/todos.spec.js | 71 +-
examples/todos/test/setup.js | 8 +-
examples/tree-view/actions/index.js | 32 +-
examples/tree-view/containers/Node.js | 71 +-
examples/tree-view/generateTree.js | 18 +-
examples/tree-view/index.js | 20 +-
examples/tree-view/reducers/index.js | 44 +-
examples/tree-view/store/configureStore.js | 14 +-
examples/tree-view/test/node.spec.js | 94 +--
examples/tree-view/test/reducer.spec.js | 172 ++---
examples/universal/client/index.js | 22 +-
examples/universal/common/actions/index.js | 32 +-
examples/universal/common/api/counter.js | 9 +-
.../universal/common/components/Counter.js | 12 +-
examples/universal/common/containers/App.js | 16 +-
examples/universal/common/reducers/counter.js | 10 +-
examples/universal/common/reducers/index.js | 10 +-
.../universal/common/store/configureStore.js | 16 +-
examples/universal/index.js | 2 +-
examples/universal/server/index.js | 4 +-
package.json | 7 +-
src/applyMiddleware.js | 24 +-
src/bindActionCreators.js | 22 +-
src/combineReducers.js | 108 +--
src/compose.js | 12 +-
src/createStore.js | 84 +--
src/index.js | 18 +-
src/utils/warning.js | 4 +-
test/applyMiddleware.spec.js | 96 +--
test/bindActionCreators.spec.js | 78 +-
test/combineReducers.spec.js | 210 +++---
test/compose.spec.js | 52 +-
test/createStore.spec.js | 666 +++++++++---------
test/helpers/actionCreators.js | 26 +-
test/helpers/actionTypes.js | 8 +-
test/helpers/middleware.js | 3 +-
test/helpers/reducers.js | 34 +-
test/typescript.spec.js | 14 +-
test/utils/warning.spec.js | 38 +-
146 files changed, 2962 insertions(+), 2929 deletions(-)
delete mode 100644 build/es3ify.js
delete mode 100644 build/use-lodash-es.js
diff --git a/.eslintrc b/.eslintrc
index 99c5dbda67..e4c371f5ce 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -1,12 +1,12 @@
{
- "extends": "rackt",
- "rules": {
- "valid-jsdoc": 2,
- // Disable until Flow supports let and const
- "no-var": 0,
- "react/jsx-uses-react": 1,
- "react/jsx-no-undef": 2,
- "react/wrap-multilines": 2
+ "extends": "airbnb",
+ "parserOptions": {
+ "ecmaVersion": 6,
+ "sourceType": "module",
+ "ecmaFeatures": {
+ "jsx": true,
+ "experimentalObjectRestSpread": true
+ },
},
"plugins": [
"react"
diff --git a/build/es3ify.js b/build/es3ify.js
deleted file mode 100644
index f4639cf400..0000000000
--- a/build/es3ify.js
+++ /dev/null
@@ -1,25 +0,0 @@
-var glob = require('glob')
-var fs = require('fs')
-var es3ify = require('es3ify')
-
-glob('./@(lib|dist|es)/**/*.js', function (err, files) {
- if (err) {
- throw err
- }
-
- files.forEach(function (file) {
- fs.readFile(file, 'utf8', function (err, data) {
- if (err) {
- throw err
- }
-
- fs.writeFile(file, es3ify.transform(data), function (err) {
- if (err) {
- throw err
- }
-
- console.log('es3ified ' + file) // eslint-disable-line no-console
- })
- })
- })
-})
diff --git a/build/use-lodash-es.js b/build/use-lodash-es.js
deleted file mode 100644
index ba4f2f52e6..0000000000
--- a/build/use-lodash-es.js
+++ /dev/null
@@ -1,10 +0,0 @@
-module.exports = function () {
- return {
- visitor: {
- ImportDeclaration(path) {
- var source = path.node.source
- source.value = source.value.replace(/^lodash($|\/)/, 'lodash-es$1')
- }
- }
- }
-}
diff --git a/examples/async/actions/index.js b/examples/async/actions/index.js
index b3c32cd68d..f8ba98a1c6 100644
--- a/examples/async/actions/index.js
+++ b/examples/async/actions/index.js
@@ -1,64 +1,64 @@
-import fetch from 'isomorphic-fetch'
+import fetch from 'isomorphic-fetch';
-export const REQUEST_POSTS = 'REQUEST_POSTS'
-export const RECEIVE_POSTS = 'RECEIVE_POSTS'
-export const SELECT_REDDIT = 'SELECT_REDDIT'
-export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT'
+export const REQUEST_POSTS = 'REQUEST_POSTS';
+export const RECEIVE_POSTS = 'RECEIVE_POSTS';
+export const SELECT_REDDIT = 'SELECT_REDDIT';
+export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT';
export function selectReddit(reddit) {
return {
type: SELECT_REDDIT,
- reddit
- }
+ reddit,
+ };
}
export function invalidateReddit(reddit) {
return {
type: INVALIDATE_REDDIT,
- reddit
- }
+ reddit,
+ };
}
function requestPosts(reddit) {
return {
type: REQUEST_POSTS,
- reddit
- }
+ reddit,
+ };
}
function receivePosts(reddit, json) {
return {
type: RECEIVE_POSTS,
- reddit: reddit,
+ reddit,
posts: json.data.children.map(child => child.data),
- receivedAt: Date.now()
- }
+ receivedAt: Date.now(),
+ };
}
function fetchPosts(reddit) {
return dispatch => {
- dispatch(requestPosts(reddit))
+ dispatch(requestPosts(reddit));
return fetch(`https://www.reddit.com/r/${reddit}.json`)
.then(response => response.json())
- .then(json => dispatch(receivePosts(reddit, json)))
- }
+ .then(json => dispatch(receivePosts(reddit, json)));
+ };
}
function shouldFetchPosts(state, reddit) {
- const posts = state.postsByReddit[reddit]
+ const posts = state.postsByReddit[reddit];
if (!posts) {
- return true
+ return true;
}
if (posts.isFetching) {
- return false
+ return false;
}
- return posts.didInvalidate
+ return posts.didInvalidate;
}
export function fetchPostsIfNeeded(reddit) {
return (dispatch, getState) => {
if (shouldFetchPosts(getState(), reddit)) {
- return dispatch(fetchPosts(reddit))
+ return dispatch(fetchPosts(reddit));
}
- }
+ };
}
diff --git a/examples/async/components/Picker.js b/examples/async/components/Picker.js
index be78acb182..e9481f0486 100644
--- a/examples/async/components/Picker.js
+++ b/examples/async/components/Picker.js
@@ -1,14 +1,16 @@
-import React, { Component, PropTypes } from 'react'
+import React, { Component, PropTypes } from 'react';
export default class Picker extends Component {
render() {
- const { value, onChange, options } = this.props
+ const { value, onChange, options } = this.props;
return (
{value}
- onChange(e.target.value)}
- value={value}>
+ onChange(e.target.value)}
+ value={value}
+ >
{options.map(option =>
{option}
@@ -16,7 +18,7 @@ export default class Picker extends Component {
}
- )
+ );
}
}
@@ -25,5 +27,5 @@ Picker.propTypes = {
PropTypes.string.isRequired
).isRequired,
value: PropTypes.string.isRequired,
- onChange: PropTypes.func.isRequired
-}
+ onChange: PropTypes.func.isRequired,
+};
diff --git a/examples/async/components/Posts.js b/examples/async/components/Posts.js
index dd3285dab9..2b4a7d0b52 100644
--- a/examples/async/components/Posts.js
+++ b/examples/async/components/Posts.js
@@ -1,4 +1,4 @@
-import React, { PropTypes, Component } from 'react'
+import React, { PropTypes, Component } from 'react';
export default class Posts extends Component {
render() {
@@ -8,10 +8,10 @@ export default class Posts extends Component {
{post.title}
)}
- )
+ );
}
}
Posts.propTypes = {
- posts: PropTypes.array.isRequired
-}
+ posts: PropTypes.array.isRequired,
+};
diff --git a/examples/async/containers/App.js b/examples/async/containers/App.js
index 6109878fca..2d8568eade 100644
--- a/examples/async/containers/App.js
+++ b/examples/async/containers/App.js
@@ -1,48 +1,49 @@
-import React, { Component, PropTypes } from 'react'
-import { connect } from 'react-redux'
-import { selectReddit, fetchPostsIfNeeded, invalidateReddit } from '../actions'
-import Picker from '../components/Picker'
-import Posts from '../components/Posts'
+import React, { Component, PropTypes } from 'react';
+import { connect } from 'react-redux';
+import { selectReddit, fetchPostsIfNeeded, invalidateReddit } from '../actions';
+import Picker from '../components/Picker';
+import Posts from '../components/Posts';
class App extends Component {
constructor(props) {
- super(props)
- this.handleChange = this.handleChange.bind(this)
- this.handleRefreshClick = this.handleRefreshClick.bind(this)
+ super(props);
+ this.handleChange = this.handleChange.bind(this);
+ this.handleRefreshClick = this.handleRefreshClick.bind(this);
}
componentDidMount() {
- const { dispatch, selectedReddit } = this.props
- dispatch(fetchPostsIfNeeded(selectedReddit))
+ const { dispatch, selectedReddit } = this.props;
+ dispatch(fetchPostsIfNeeded(selectedReddit));
}
componentWillReceiveProps(nextProps) {
if (nextProps.selectedReddit !== this.props.selectedReddit) {
- const { dispatch, selectedReddit } = nextProps
- dispatch(fetchPostsIfNeeded(selectedReddit))
+ const { dispatch, selectedReddit } = nextProps;
+ dispatch(fetchPostsIfNeeded(selectedReddit));
}
}
handleChange(nextReddit) {
- this.props.dispatch(selectReddit(nextReddit))
+ this.props.dispatch(selectReddit(nextReddit));
}
handleRefreshClick(e) {
- e.preventDefault()
+ e.preventDefault();
- const { dispatch, selectedReddit } = this.props
- dispatch(invalidateReddit(selectedReddit))
- dispatch(fetchPostsIfNeeded(selectedReddit))
+ const { dispatch, selectedReddit } = this.props;
+ dispatch(invalidateReddit(selectedReddit));
+ dispatch(fetchPostsIfNeeded(selectedReddit));
}
render() {
- const { selectedReddit, posts, isFetching, lastUpdated } = this.props
- const isEmpty = posts.length === 0
+ const { selectedReddit, posts, isFetching, lastUpdated } = this.props;
+ const isEmpty = posts.length === 0;
return (
+ onChange={this.handleChange}
+ options={['reactjs', 'frontend']}
+ />
{lastUpdated &&
@@ -52,19 +53,20 @@ class App extends Component {
}
{!isFetching &&
+ onClick={this.handleRefreshClick}
+ >
Refresh
}
- {isEmpty
- ? (isFetching ?
Loading... :
Empty. )
- :
- }
+ {isEmpty
+ ? (isFetching ?
Loading... :
Empty. )
+ :
+ }
- )
+ );
}
}
@@ -73,26 +75,26 @@ App.propTypes = {
posts: PropTypes.array.isRequired,
isFetching: PropTypes.bool.isRequired,
lastUpdated: PropTypes.number,
- dispatch: PropTypes.func.isRequired
-}
+ dispatch: PropTypes.func.isRequired,
+};
function mapStateToProps(state) {
- const { selectedReddit, postsByReddit } = state
+ const { selectedReddit, postsByReddit } = state;
const {
isFetching,
lastUpdated,
- items: posts
+ items: posts,
} = postsByReddit[selectedReddit] || {
isFetching: true,
- items: []
- }
+ items: [],
+ };
return {
selectedReddit,
posts,
isFetching,
- lastUpdated
- }
+ lastUpdated,
+ };
}
-export default connect(mapStateToProps)(App)
+export default connect(mapStateToProps)(App);
diff --git a/examples/async/index.js b/examples/async/index.js
index 12bcb25c37..ab639cc882 100644
--- a/examples/async/index.js
+++ b/examples/async/index.js
@@ -1,15 +1,15 @@
-import 'babel-polyfill'
-import React from 'react'
-import { render } from 'react-dom'
-import { Provider } from 'react-redux'
-import App from './containers/App'
-import configureStore from './store/configureStore'
+import 'babel-polyfill';
+import React from 'react';
+import { render } from 'react-dom';
+import { Provider } from 'react-redux';
+import App from './containers/App';
+import configureStore from './store/configureStore';
-const store = configureStore()
+const store = configureStore();
render(
,
document.getElementById('root')
-)
+);
diff --git a/examples/async/reducers/index.js b/examples/async/reducers/index.js
index f936cbced3..d79c407a33 100644
--- a/examples/async/reducers/index.js
+++ b/examples/async/reducers/index.js
@@ -1,42 +1,42 @@
-import { combineReducers } from 'redux'
+import { combineReducers } from 'redux';
import {
SELECT_REDDIT, INVALIDATE_REDDIT,
- REQUEST_POSTS, RECEIVE_POSTS
-} from '../actions'
+ REQUEST_POSTS, RECEIVE_POSTS,
+} from '../actions';
function selectedReddit(state = 'reactjs', action) {
switch (action.type) {
case SELECT_REDDIT:
- return action.reddit
+ return action.reddit;
default:
- return state
+ return state;
}
}
function posts(state = {
isFetching: false,
didInvalidate: false,
- items: []
+ items: [],
}, action) {
switch (action.type) {
case INVALIDATE_REDDIT:
return Object.assign({}, state, {
- didInvalidate: true
- })
+ didInvalidate: true,
+ });
case REQUEST_POSTS:
return Object.assign({}, state, {
isFetching: true,
- didInvalidate: false
- })
+ didInvalidate: false,
+ });
case RECEIVE_POSTS:
return Object.assign({}, state, {
isFetching: false,
didInvalidate: false,
items: action.posts,
- lastUpdated: action.receivedAt
- })
+ lastUpdated: action.receivedAt,
+ });
default:
- return state
+ return state;
}
}
@@ -46,16 +46,16 @@ function postsByReddit(state = { }, action) {
case RECEIVE_POSTS:
case REQUEST_POSTS:
return Object.assign({}, state, {
- [action.reddit]: posts(state[action.reddit], action)
- })
+ [action.reddit]: posts(state[action.reddit], action),
+ });
default:
- return state
+ return state;
}
}
const rootReducer = combineReducers({
postsByReddit,
- selectedReddit
-})
+ selectedReddit,
+});
-export default rootReducer
+export default rootReducer;
diff --git a/examples/async/store/configureStore.js b/examples/async/store/configureStore.js
index 465d94919a..8767d763e7 100644
--- a/examples/async/store/configureStore.js
+++ b/examples/async/store/configureStore.js
@@ -1,22 +1,22 @@
-import { createStore, applyMiddleware } from 'redux'
-import thunkMiddleware from 'redux-thunk'
-import createLogger from 'redux-logger'
-import rootReducer from '../reducers'
+import { createStore, applyMiddleware } from 'redux';
+import thunkMiddleware from 'redux-thunk';
+import createLogger from 'redux-logger';
+import rootReducer from '../reducers';
export default function configureStore(initialState) {
const store = createStore(
rootReducer,
initialState,
applyMiddleware(thunkMiddleware, createLogger())
- )
+ );
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
- const nextRootReducer = require('../reducers').default
- store.replaceReducer(nextRootReducer)
- })
+ const nextRootReducer = require('../reducers').default;
+ store.replaceReducer(nextRootReducer);
+ });
}
- return store
+ return store;
}
diff --git a/examples/buildAll.js b/examples/buildAll.js
index 82388984b0..6cd8ed73cf 100644
--- a/examples/buildAll.js
+++ b/examples/buildAll.js
@@ -2,35 +2,35 @@
* Runs an ordered set of commands within each of the build directories.
*/
-import fs from 'fs'
-import path from 'path'
-import { spawnSync } from 'child_process'
+import fs from 'fs';
+import path from 'path';
+import { spawnSync } from 'child_process';
-var exampleDirs = fs.readdirSync(__dirname).filter((file) => {
- return fs.statSync(path.join(__dirname, file)).isDirectory()
-})
+const exampleDirs = fs.readdirSync(__dirname).filter((file) =>
+ fs.statSync(path.join(__dirname, file)).isDirectory()
+);
// Ordering is important here. `npm install` must come first.
-var cmdArgs = [
- { cmd: 'npm', args: [ 'install' ] },
- { cmd: 'webpack', args: [ 'index.js' ] }
-]
+const cmdArgs = [
+ { cmd: 'npm', args: ['install'] },
+ { cmd: 'webpack', args: ['index.js'] },
+];
for (const dir of exampleDirs) {
for (const cmdArg of cmdArgs) {
// declare opts in this scope to avoid https://github.com/joyent/node/issues/9158
const opts = {
cwd: path.join(__dirname, dir),
- stdio: 'inherit'
- }
- let result = {}
+ stdio: 'inherit',
+ };
+ let result = {};
if (process.platform === 'win32') {
- result = spawnSync(cmdArg.cmd + '.cmd', cmdArg.args, opts)
+ result = spawnSync(`${cmdArg.cmd}.cmd`, cmdArg.args, opts);
} else {
- result = spawnSync(cmdArg.cmd, cmdArg.args, opts)
+ result = spawnSync(cmdArg.cmd, cmdArg.args, opts);
}
if (result.status !== 0) {
- throw new Error('Building examples exited with non-zero')
+ throw new Error('Building examples exited with non-zero');
}
}
}
diff --git a/examples/counter/components/Counter.js b/examples/counter/components/Counter.js
index ef473bf933..0007289e2a 100644
--- a/examples/counter/components/Counter.js
+++ b/examples/counter/components/Counter.js
@@ -1,24 +1,24 @@
-import React, { Component, PropTypes } from 'react'
+import React, { Component, PropTypes } from 'react';
class Counter extends Component {
constructor(props) {
- super(props)
- this.incrementAsync = this.incrementAsync.bind(this)
- this.incrementIfOdd = this.incrementIfOdd.bind(this)
+ super(props);
+ this.incrementAsync = this.incrementAsync.bind(this);
+ this.incrementIfOdd = this.incrementIfOdd.bind(this);
}
incrementIfOdd() {
if (this.props.value % 2 !== 0) {
- this.props.onIncrement()
+ this.props.onIncrement();
}
}
incrementAsync() {
- setTimeout(this.props.onIncrement, 1000)
+ setTimeout(this.props.onIncrement, 1000);
}
render() {
- const { value, onIncrement, onDecrement } = this.props
+ const { value, onIncrement, onDecrement } = this.props;
return (
Clicked: {value} times
@@ -39,14 +39,14 @@ class Counter extends Component {
Increment async
- )
+ );
}
}
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
- onDecrement: PropTypes.func.isRequired
-}
+ onDecrement: PropTypes.func.isRequired,
+};
-export default Counter
+export default Counter;
diff --git a/examples/counter/index.js b/examples/counter/index.js
index 60cac9cf27..8b18cc420f 100644
--- a/examples/counter/index.js
+++ b/examples/counter/index.js
@@ -1,11 +1,11 @@
-import React from 'react'
-import ReactDOM from 'react-dom'
-import { createStore } from 'redux'
-import Counter from './components/Counter'
-import counter from './reducers'
+import React from 'react';
+import ReactDOM from 'react-dom';
+import { createStore } from 'redux';
+import Counter from './components/Counter';
+import counter from './reducers';
-const store = createStore(counter)
-const rootEl = document.getElementById('root')
+const store = createStore(counter);
+const rootEl = document.getElementById('root');
function render() {
ReactDOM.render(
@@ -14,9 +14,9 @@ function render() {
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>,
- rootEl
- )
+ rootEl
+ );
}
-render()
-store.subscribe(render)
+render();
+store.subscribe(render);
diff --git a/examples/counter/reducers/index.js b/examples/counter/reducers/index.js
index 49590e9b05..b59edeb76a 100644
--- a/examples/counter/reducers/index.js
+++ b/examples/counter/reducers/index.js
@@ -1,10 +1,10 @@
export default function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
- return state + 1
+ return state + 1;
case 'DECREMENT':
- return state - 1
+ return state - 1;
default:
- return state
+ return state;
}
}
diff --git a/examples/counter/test/components/Counter.spec.js b/examples/counter/test/components/Counter.spec.js
index 4e5258d0ad..7474bd5b4d 100644
--- a/examples/counter/test/components/Counter.spec.js
+++ b/examples/counter/test/components/Counter.spec.js
@@ -1,67 +1,67 @@
-import expect from 'expect'
-import React from 'react'
-import { shallow } from 'enzyme'
-import Counter from '../../components/Counter'
+import expect from 'expect';
+import React from 'react';
+import { shallow } from 'enzyme';
+import Counter from '../../components/Counter';
function setup(value = 0) {
const actions = {
onIncrement: expect.createSpy(),
onDecrement: expect.createSpy()
- }
+ };
const component = shallow(
- )
+ );
return {
- component: component,
- actions: actions,
+ component,
+ actions,
buttons: component.find('button'),
- p: component.find('p')
- }
+ p: component.find('p'),
+ };
}
describe('Counter component', () => {
it('should display count', () => {
- const { p } = setup()
- expect(p.text()).toMatch(/^Clicked: 0 times/)
- })
+ const { p } = setup();
+ expect(p.text()).toMatch(/^Clicked: 0 times/);
+ });
it('first button should call onIncrement', () => {
- const { buttons, actions } = setup()
- buttons.at(0).simulate('click')
- expect(actions.onIncrement).toHaveBeenCalled()
- })
+ const { buttons, actions } = setup();
+ buttons.at(0).simulate('click');
+ expect(actions.onIncrement).toHaveBeenCalled();
+ });
it('second button should call onDecrement', () => {
- const { buttons, actions } = setup()
- buttons.at(1).simulate('click')
- expect(actions.onDecrement).toHaveBeenCalled()
- })
+ const { buttons, actions } = setup();
+ buttons.at(1).simulate('click');
+ expect(actions.onDecrement).toHaveBeenCalled();
+ });
it('third button should not call onIncrement if the counter is even', () => {
- const { buttons, actions } = setup(42)
- buttons.at(2).simulate('click')
- expect(actions.onIncrement).toNotHaveBeenCalled()
- })
+ const { buttons, actions } = setup(42);
+ buttons.at(2).simulate('click');
+ expect(actions.onIncrement).toNotHaveBeenCalled();
+ });
it('third button should call onIncrement if the counter is odd', () => {
- const { buttons, actions } = setup(43)
- buttons.at(2).simulate('click')
- expect(actions.onIncrement).toHaveBeenCalled()
- })
+ const { buttons, actions } = setup(43);
+ buttons.at(2).simulate('click');
+ expect(actions.onIncrement).toHaveBeenCalled();
+ });
it('third button should call onIncrement if the counter is odd and negative', () => {
- const { buttons, actions } = setup(-43)
- buttons.at(2).simulate('click')
- expect(actions.onIncrement).toHaveBeenCalled()
- })
+ const { buttons, actions } = setup(-43);
+ buttons.at(2).simulate('click');
+ expect(actions.onIncrement).toHaveBeenCalled();
+ });
it('fourth button should call onIncrement in a second', (done) => {
- const { buttons, actions } = setup()
- buttons.at(3).simulate('click')
+ const { buttons, actions } = setup();
+ buttons.at(3).simulate('click');
setTimeout(() => {
- expect(actions.onIncrement).toHaveBeenCalled()
- done()
- }, 1000)
- })
-})
+ expect(actions.onIncrement).toHaveBeenCalled();
+ done();
+ }, 1000);
+ });
+});
diff --git a/examples/counter/test/reducers/counter.spec.js b/examples/counter/test/reducers/counter.spec.js
index c51d16adf4..411990c547 100644
--- a/examples/counter/test/reducers/counter.spec.js
+++ b/examples/counter/test/reducers/counter.spec.js
@@ -1,22 +1,22 @@
-import expect from 'expect'
-import counter from '../../reducers'
+import expect from 'expect';
+import counter from '../../reducers';
describe('reducers', () => {
describe('counter', () => {
it('should provide the initial state', () => {
- expect(counter(undefined, {})).toBe(0)
- })
+ expect(counter(undefined, {})).toBe(0);
+ });
it('should handle INCREMENT action', () => {
- expect(counter(1, { type: 'INCREMENT' })).toBe(2)
- })
+ expect(counter(1, { type: 'INCREMENT' })).toBe(2);
+ });
it('should handle DECREMENT action', () => {
- expect(counter(1, { type: 'DECREMENT' })).toBe(0)
- })
+ expect(counter(1, { type: 'DECREMENT' })).toBe(0);
+ });
it('should ignore unknown actions', () => {
- expect(counter(1, { type: 'unknown' })).toBe(1)
- })
- })
-})
+ expect(counter(1, { type: 'unknown' })).toBe(1);
+ });
+ });
+});
diff --git a/examples/real-world/actions/index.js b/examples/real-world/actions/index.js
index 2692fcb069..78961be66e 100644
--- a/examples/real-world/actions/index.js
+++ b/examples/real-world/actions/index.js
@@ -1,66 +1,66 @@
-import { CALL_API, Schemas } from '../middleware/api'
+import { CALL_API, Schemas } from '../middleware/api';
-export const USER_REQUEST = 'USER_REQUEST'
-export const USER_SUCCESS = 'USER_SUCCESS'
-export const USER_FAILURE = 'USER_FAILURE'
+export const USER_REQUEST = 'USER_REQUEST';
+export const USER_SUCCESS = 'USER_SUCCESS';
+export const USER_FAILURE = 'USER_FAILURE';
// Fetches a single user from Github API.
// Relies on the custom API middleware defined in ../middleware/api.js.
function fetchUser(login) {
return {
[CALL_API]: {
- types: [ USER_REQUEST, USER_SUCCESS, USER_FAILURE ],
+ types: [USER_REQUEST, USER_SUCCESS, USER_FAILURE],
endpoint: `users/${login}`,
- schema: Schemas.USER
- }
- }
+ schema: Schemas.USER,
+ },
+ };
}
// Fetches a single user from Github API unless it is cached.
// Relies on Redux Thunk middleware.
export function loadUser(login, requiredFields = []) {
return (dispatch, getState) => {
- const user = getState().entities.users[login]
+ const user = getState().entities.users[login];
if (user && requiredFields.every(key => user.hasOwnProperty(key))) {
- return null
+ return null;
}
- return dispatch(fetchUser(login))
- }
+ return dispatch(fetchUser(login));
+ };
}
-export const REPO_REQUEST = 'REPO_REQUEST'
-export const REPO_SUCCESS = 'REPO_SUCCESS'
-export const REPO_FAILURE = 'REPO_FAILURE'
+export const REPO_REQUEST = 'REPO_REQUEST';
+export const REPO_SUCCESS = 'REPO_SUCCESS';
+export const REPO_FAILURE = 'REPO_FAILURE';
// Fetches a single repository from Github API.
// Relies on the custom API middleware defined in ../middleware/api.js.
function fetchRepo(fullName) {
return {
[CALL_API]: {
- types: [ REPO_REQUEST, REPO_SUCCESS, REPO_FAILURE ],
+ types: [REPO_REQUEST, REPO_SUCCESS, REPO_FAILURE],
endpoint: `repos/${fullName}`,
- schema: Schemas.REPO
- }
- }
+ schema: Schemas.REPO,
+ },
+ };
}
// Fetches a single repository from Github API unless it is cached.
// Relies on Redux Thunk middleware.
export function loadRepo(fullName, requiredFields = []) {
return (dispatch, getState) => {
- const repo = getState().entities.repos[fullName]
+ const repo = getState().entities.repos[fullName];
if (repo && requiredFields.every(key => repo.hasOwnProperty(key))) {
- return null
+ return null;
}
- return dispatch(fetchRepo(fullName))
- }
+ return dispatch(fetchRepo(fullName));
+ };
}
-export const STARRED_REQUEST = 'STARRED_REQUEST'
-export const STARRED_SUCCESS = 'STARRED_SUCCESS'
-export const STARRED_FAILURE = 'STARRED_FAILURE'
+export const STARRED_REQUEST = 'STARRED_REQUEST';
+export const STARRED_SUCCESS = 'STARRED_SUCCESS';
+export const STARRED_FAILURE = 'STARRED_FAILURE';
// Fetches a page of starred repos by a particular user.
// Relies on the custom API middleware defined in ../middleware/api.js.
@@ -68,11 +68,11 @@ function fetchStarred(login, nextPageUrl) {
return {
login,
[CALL_API]: {
- types: [ STARRED_REQUEST, STARRED_SUCCESS, STARRED_FAILURE ],
+ types: [STARRED_REQUEST, STARRED_SUCCESS, STARRED_FAILURE],
endpoint: nextPageUrl,
- schema: Schemas.REPO_ARRAY
- }
- }
+ schema: Schemas.REPO_ARRAY,
+ },
+ };
}
// Fetches a page of starred repos by a particular user.
@@ -82,20 +82,20 @@ export function loadStarred(login, nextPage) {
return (dispatch, getState) => {
const {
nextPageUrl = `users/${login}/starred`,
- pageCount = 0
- } = getState().pagination.starredByUser[login] || {}
+ pageCount = 0,
+ } = getState().pagination.starredByUser[login] || {};
if (pageCount > 0 && !nextPage) {
- return null
+ return null;
}
- return dispatch(fetchStarred(login, nextPageUrl))
- }
+ return dispatch(fetchStarred(login, nextPageUrl));
+ };
}
-export const STARGAZERS_REQUEST = 'STARGAZERS_REQUEST'
-export const STARGAZERS_SUCCESS = 'STARGAZERS_SUCCESS'
-export const STARGAZERS_FAILURE = 'STARGAZERS_FAILURE'
+export const STARGAZERS_REQUEST = 'STARGAZERS_REQUEST';
+export const STARGAZERS_SUCCESS = 'STARGAZERS_SUCCESS';
+export const STARGAZERS_FAILURE = 'STARGAZERS_FAILURE';
// Fetches a page of stargazers for a particular repo.
// Relies on the custom API middleware defined in ../middleware/api.js.
@@ -103,11 +103,11 @@ function fetchStargazers(fullName, nextPageUrl) {
return {
fullName,
[CALL_API]: {
- types: [ STARGAZERS_REQUEST, STARGAZERS_SUCCESS, STARGAZERS_FAILURE ],
+ types: [STARGAZERS_REQUEST, STARGAZERS_SUCCESS, STARGAZERS_FAILURE],
endpoint: nextPageUrl,
- schema: Schemas.USER_ARRAY
- }
- }
+ schema: Schemas.USER_ARRAY,
+ },
+ };
}
// Fetches a page of stargazers for a particular repo.
@@ -117,22 +117,22 @@ export function loadStargazers(fullName, nextPage) {
return (dispatch, getState) => {
const {
nextPageUrl = `repos/${fullName}/stargazers`,
- pageCount = 0
- } = getState().pagination.stargazersByRepo[fullName] || {}
+ pageCount = 0,
+ } = getState().pagination.stargazersByRepo[fullName] || {};
if (pageCount > 0 && !nextPage) {
- return null
+ return null;
}
- return dispatch(fetchStargazers(fullName, nextPageUrl))
- }
+ return dispatch(fetchStargazers(fullName, nextPageUrl));
+ };
}
-export const RESET_ERROR_MESSAGE = 'RESET_ERROR_MESSAGE'
+export const RESET_ERROR_MESSAGE = 'RESET_ERROR_MESSAGE';
// Resets the currently visible error message.
export function resetErrorMessage() {
return {
- type: RESET_ERROR_MESSAGE
- }
+ type: RESET_ERROR_MESSAGE,
+ };
}
diff --git a/examples/real-world/components/Explore.js b/examples/real-world/components/Explore.js
index e83051d3bb..30bc6e310f 100644
--- a/examples/real-world/components/Explore.js
+++ b/examples/real-world/components/Explore.js
@@ -1,39 +1,39 @@
-import React, { Component, PropTypes } from 'react'
+import React, { Component, PropTypes } from 'react';
-const GITHUB_REPO = 'https://github.com/reactjs/redux'
+const GITHUB_REPO = 'https://github.com/reactjs/redux';
export default class Explore extends Component {
constructor(props) {
- super(props)
- this.handleKeyUp = this.handleKeyUp.bind(this)
- this.handleGoClick = this.handleGoClick.bind(this)
+ super(props);
+ this.handleKeyUp = this.handleKeyUp.bind(this);
+ this.handleGoClick = this.handleGoClick.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.props.value) {
- this.setInputValue(nextProps.value)
+ this.setInputValue(nextProps.value);
}
}
getInputValue() {
- return this.refs.input.value
+ return this.refs.input.value;
}
setInputValue(val) {
// Generally mutating DOM is a bad idea in React components,
// but doing this for a single uncontrolled field is less fuss
// than making it controlled and maintaining a state for it.
- this.refs.input.value = val
+ this.refs.input.value = val;
}
handleKeyUp(e) {
if (e.keyCode === 13) {
- this.handleGoClick()
+ this.handleGoClick();
}
}
handleGoClick() {
- this.props.onChange(this.getInputValue())
+ this.props.onChange(this.getInputValue());
}
render() {
@@ -41,9 +41,10 @@ export default class Explore extends Component {
Type a username or repo full name and hit 'Go':
+ ref="input"
+ defaultValue={this.props.value}
+ onKeyUp={this.handleKeyUp}
+ />
Go!
@@ -54,11 +55,11 @@ export default class Explore extends Component {
Move the DevTools with Ctrl+W or hide them with Ctrl+H.
- )
+ );
}
}
Explore.propTypes = {
value: PropTypes.string.isRequired,
- onChange: PropTypes.func.isRequired
-}
+ onChange: PropTypes.func.isRequired,
+};
diff --git a/examples/real-world/components/List.js b/examples/real-world/components/List.js
index 9fad1c9ddd..306a6b03fa 100644
--- a/examples/real-world/components/List.js
+++ b/examples/real-world/components/List.js
@@ -1,31 +1,32 @@
-import React, { Component, PropTypes } from 'react'
+import React, { Component, PropTypes } from 'react';
export default class List extends Component {
renderLoadMore() {
- const { isFetching, onLoadMoreClick } = this.props
+ const { isFetching, onLoadMoreClick } = this.props;
return (
+ onClick={onLoadMoreClick}
+ disabled={isFetching}
+ >
{isFetching ? 'Loading...' : 'Load More'}
- )
+ );
}
render() {
const {
isFetching, nextPageUrl, pageCount,
- items, renderItem, loadingLabel
- } = this.props
+ items, renderItem, loadingLabel,
+ } = this.props;
- const isEmpty = items.length === 0
+ const isEmpty = items.length === 0;
if (isEmpty && isFetching) {
- return {loadingLabel}
+ return {loadingLabel} ;
}
- const isLastPage = !nextPageUrl
+ const isLastPage = !nextPageUrl;
if (isEmpty && isLastPage) {
- return Nothing here!
+ return Nothing here! ;
}
return (
@@ -33,7 +34,7 @@ export default class List extends Component {
{items.map(renderItem)}
{pageCount > 0 && !isLastPage && this.renderLoadMore()}
- )
+ );
}
}
@@ -44,10 +45,10 @@ List.propTypes = {
items: PropTypes.array.isRequired,
isFetching: PropTypes.bool.isRequired,
onLoadMoreClick: PropTypes.func.isRequired,
- nextPageUrl: PropTypes.string
-}
+ nextPageUrl: PropTypes.string,
+};
List.defaultProps = {
isFetching: true,
- loadingLabel: 'Loading...'
-}
+ loadingLabel: 'Loading...',
+};
diff --git a/examples/real-world/components/Repo.js b/examples/real-world/components/Repo.js
index a9754e110f..480b9932e6 100644
--- a/examples/real-world/components/Repo.js
+++ b/examples/real-world/components/Repo.js
@@ -1,12 +1,12 @@
-import React, { Component, PropTypes } from 'react'
-import { Link } from 'react-router'
+import React, { Component, PropTypes } from 'react';
+import { Link } from 'react-router';
export default class Repo extends Component {
render() {
- const { repo, owner } = this.props
- const { login } = owner
- const { name, description } = repo
+ const { repo, owner } = this.props;
+ const { login } = owner;
+ const { name, description } = repo;
return (
@@ -23,16 +23,16 @@ export default class Repo extends Component {
{description}
}
- )
+ );
}
}
Repo.propTypes = {
repo: PropTypes.shape({
name: PropTypes.string.isRequired,
- description: PropTypes.string
+ description: PropTypes.string,
}).isRequired,
owner: PropTypes.shape({
- login: PropTypes.string.isRequired
- }).isRequired
-}
+ login: PropTypes.string.isRequired,
+ }).isRequired,
+};
diff --git a/examples/real-world/components/User.js b/examples/real-world/components/User.js
index c52ade2a3a..455b9942c8 100644
--- a/examples/real-world/components/User.js
+++ b/examples/real-world/components/User.js
@@ -1,9 +1,9 @@
-import React, { Component, PropTypes } from 'react'
-import { Link } from 'react-router'
+import React, { Component, PropTypes } from 'react';
+import { Link } from 'react-router';
export default class User extends Component {
render() {
- const { login, avatarUrl, name } = this.props.user
+ const { login, avatarUrl, name } = this.props.user;
return (
@@ -14,7 +14,7 @@ export default class User extends Component {
- )
+ );
}
}
@@ -22,6 +22,6 @@ User.propTypes = {
user: PropTypes.shape({
login: PropTypes.string.isRequired,
avatarUrl: PropTypes.string.isRequired,
- name: PropTypes.string
- }).isRequired
-}
+ name: PropTypes.string,
+ }).isRequired,
+};
diff --git a/examples/real-world/containers/App.js b/examples/real-world/containers/App.js
index f7db3cd2b8..545f2665bf 100644
--- a/examples/real-world/containers/App.js
+++ b/examples/real-world/containers/App.js
@@ -1,29 +1,29 @@
-import React, { Component, PropTypes } from 'react'
-import { connect } from 'react-redux'
-import { browserHistory } from 'react-router'
-import Explore from '../components/Explore'
-import { resetErrorMessage } from '../actions'
+import React, { Component, PropTypes } from 'react';
+import { connect } from 'react-redux';
+import { browserHistory } from 'react-router';
+import Explore from '../components/Explore';
+import { resetErrorMessage } from '../actions';
class App extends Component {
constructor(props) {
- super(props)
- this.handleChange = this.handleChange.bind(this)
- this.handleDismissClick = this.handleDismissClick.bind(this)
+ super(props);
+ this.handleChange = this.handleChange.bind(this);
+ this.handleDismissClick = this.handleDismissClick.bind(this);
}
handleDismissClick(e) {
- this.props.resetErrorMessage()
- e.preventDefault()
+ this.props.resetErrorMessage();
+ e.preventDefault();
}
handleChange(nextValue) {
- browserHistory.push(`/${nextValue}`)
+ browserHistory.push(`/${nextValue}`);
}
renderErrorMessage() {
- const { errorMessage } = this.props
+ const { errorMessage } = this.props;
if (!errorMessage) {
- return null
+ return null;
}
return (
@@ -31,24 +31,26 @@ class App extends Component {
{errorMessage}
{' '}
(
+ onClick={this.handleDismissClick}
+ >
Dismiss
)
- )
+ );
}
render() {
- const { children, inputValue } = this.props
+ const { children, inputValue } = this.props;
return (
+ onChange={this.handleChange}
+ />
{this.renderErrorMessage()}
{children}
- )
+ );
}
}
@@ -58,16 +60,16 @@ App.propTypes = {
resetErrorMessage: PropTypes.func.isRequired,
inputValue: PropTypes.string.isRequired,
// Injected by React Router
- children: PropTypes.node
-}
+ children: PropTypes.node,
+};
function mapStateToProps(state, ownProps) {
return {
errorMessage: state.errorMessage,
- inputValue: ownProps.location.pathname.substring(1)
- }
+ inputValue: ownProps.location.pathname.substring(1),
+ };
}
export default connect(mapStateToProps, {
- resetErrorMessage
-})(App)
+ resetErrorMessage,
+})(App);
diff --git a/examples/real-world/containers/DevTools.js b/examples/real-world/containers/DevTools.js
index ad1b6fdc71..64e9a71a2e 100644
--- a/examples/real-world/containers/DevTools.js
+++ b/examples/real-world/containers/DevTools.js
@@ -1,11 +1,12 @@
-import React from 'react'
-import { createDevTools } from 'redux-devtools'
-import LogMonitor from 'redux-devtools-log-monitor'
-import DockMonitor from 'redux-devtools-dock-monitor'
+import React from 'react';
+import { createDevTools } from 'redux-devtools';
+import LogMonitor from 'redux-devtools-log-monitor';
+import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
+ changePositionKey="ctrl-w"
+ >
-)
+);
diff --git a/examples/real-world/containers/RepoPage.js b/examples/real-world/containers/RepoPage.js
index e5e62c7c30..9f03d49110 100644
--- a/examples/real-world/containers/RepoPage.js
+++ b/examples/real-world/containers/RepoPage.js
@@ -1,63 +1,66 @@
-import React, { Component, PropTypes } from 'react'
-import { connect } from 'react-redux'
-import { loadRepo, loadStargazers } from '../actions'
-import Repo from '../components/Repo'
-import User from '../components/User'
-import List from '../components/List'
+import React, { Component, PropTypes } from 'react';
+import { connect } from 'react-redux';
+import { loadRepo, loadStargazers } from '../actions';
+import Repo from '../components/Repo';
+import User from '../components/User';
+import List from '../components/List';
function loadData(props) {
- const { fullName } = props
- props.loadRepo(fullName, [ 'description' ])
- props.loadStargazers(fullName)
+ const { fullName } = props;
+ props.loadRepo(fullName, ['description']);
+ props.loadStargazers(fullName);
}
class RepoPage extends Component {
constructor(props) {
- super(props)
- this.renderUser = this.renderUser.bind(this)
- this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this)
+ super(props);
+ this.renderUser = this.renderUser.bind(this);
+ this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this);
}
componentWillMount() {
- loadData(this.props)
+ loadData(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.fullName !== this.props.fullName) {
- loadData(nextProps)
+ loadData(nextProps);
}
}
handleLoadMoreClick() {
- this.props.loadStargazers(this.props.fullName, true)
+ this.props.loadStargazers(this.props.fullName, true);
}
renderUser(user) {
return (
- )
+ key={user.login}
+ />
+ );
}
render() {
- const { repo, owner, name } = this.props
+ const { repo, owner, name } = this.props;
if (!repo || !owner) {
- return Loading {name} details...
+ return Loading {name} details... ;
}
- const { stargazers, stargazersPagination } = this.props
+ const { stargazers, stargazersPagination } = this.props;
return (
+ owner={owner}
+ />
+ items={stargazers}
+ onLoadMoreClick={this.handleLoadMoreClick}
+ loadingLabel={`Loading stargazers of ${name}...`}
+ {...stargazersPagination}
+ />
- )
+ );
}
}
@@ -69,19 +72,19 @@ RepoPage.propTypes = {
stargazers: PropTypes.array.isRequired,
stargazersPagination: PropTypes.object,
loadRepo: PropTypes.func.isRequired,
- loadStargazers: PropTypes.func.isRequired
-}
+ loadStargazers: PropTypes.func.isRequired,
+};
function mapStateToProps(state, ownProps) {
- const { login, name } = ownProps.params
+ const { login, name } = ownProps.params;
const {
pagination: { stargazersByRepo },
- entities: { users, repos }
- } = state
+ entities: { users, repos },
+ } = state;
- const fullName = `${login}/${name}`
- const stargazersPagination = stargazersByRepo[fullName] || { ids: [] }
- const stargazers = stargazersPagination.ids.map(id => users[id])
+ const fullName = `${login}/${name}`;
+ const stargazersPagination = stargazersByRepo[fullName] || { ids: [] };
+ const stargazers = stargazersPagination.ids.map(id => users[id]);
return {
fullName,
@@ -89,11 +92,11 @@ function mapStateToProps(state, ownProps) {
stargazers,
stargazersPagination,
repo: repos[fullName],
- owner: users[login]
- }
+ owner: users[login],
+ };
}
export default connect(mapStateToProps, {
loadRepo,
- loadStargazers
-})(RepoPage)
+ loadStargazers,
+})(RepoPage);
diff --git a/examples/real-world/containers/Root.dev.js b/examples/real-world/containers/Root.dev.js
index 8645b5c60c..d8e53750c2 100644
--- a/examples/real-world/containers/Root.dev.js
+++ b/examples/real-world/containers/Root.dev.js
@@ -1,12 +1,12 @@
-import React, { Component, PropTypes } from 'react'
-import { Provider } from 'react-redux'
-import routes from '../routes'
-import DevTools from './DevTools'
-import { Router } from 'react-router'
+import React, { Component, PropTypes } from 'react';
+import { Provider } from 'react-redux';
+import routes from '../routes';
+import DevTools from './DevTools';
+import { Router } from 'react-router';
export default class Root extends Component {
render() {
- const { store, history } = this.props
+ const { store, history } = this.props;
return (
@@ -14,11 +14,11 @@ export default class Root extends Component {
- )
+ );
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
- history: PropTypes.object.isRequired
-}
+ history: PropTypes.object.isRequired,
+};
diff --git a/examples/real-world/containers/Root.js b/examples/real-world/containers/Root.js
index 47900aa892..9cea0b2263 100644
--- a/examples/real-world/containers/Root.js
+++ b/examples/real-world/containers/Root.js
@@ -1,5 +1,5 @@
if (process.env.NODE_ENV === 'production') {
- module.exports = require('./Root.prod')
+ module.exports = require('./Root.prod');
} else {
- module.exports = require('./Root.dev')
+ module.exports = require('./Root.dev');
}
diff --git a/examples/real-world/containers/Root.prod.js b/examples/real-world/containers/Root.prod.js
index bb7a16eb13..44d81717f1 100644
--- a/examples/real-world/containers/Root.prod.js
+++ b/examples/real-world/containers/Root.prod.js
@@ -1,20 +1,20 @@
-import React, { Component, PropTypes } from 'react'
-import { Provider } from 'react-redux'
-import routes from '../routes'
-import { Router } from 'react-router'
+import React, { Component, PropTypes } from 'react';
+import { Provider } from 'react-redux';
+import routes from '../routes';
+import { Router } from 'react-router';
export default class Root extends Component {
render() {
- const { store, history } = this.props
+ const { store, history } = this.props;
return (
- )
+ );
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
- history: PropTypes.object.isRequired
-}
+ history: PropTypes.object.isRequired,
+};
diff --git a/examples/real-world/containers/UserPage.js b/examples/real-world/containers/UserPage.js
index 29a25f0220..55fba689bf 100644
--- a/examples/real-world/containers/UserPage.js
+++ b/examples/real-world/containers/UserPage.js
@@ -1,64 +1,66 @@
-import React, { Component, PropTypes } from 'react'
-import { connect } from 'react-redux'
-import { loadUser, loadStarred } from '../actions'
-import User from '../components/User'
-import Repo from '../components/Repo'
-import List from '../components/List'
-import zip from 'lodash/zip'
+import React, { Component, PropTypes } from 'react';
+import { connect } from 'react-redux';
+import { loadUser, loadStarred } from '../actions';
+import User from '../components/User';
+import Repo from '../components/Repo';
+import List from '../components/List';
+import zip from 'lodash/zip';
function loadData(props) {
- const { login } = props
- props.loadUser(login, [ 'name' ])
- props.loadStarred(login)
+ const { login } = props;
+ props.loadUser(login, ['name']);
+ props.loadStarred(login);
}
class UserPage extends Component {
constructor(props) {
- super(props)
- this.renderRepo = this.renderRepo.bind(this)
- this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this)
+ super(props);
+ this.renderRepo = this.renderRepo.bind(this);
+ this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this);
}
componentWillMount() {
- loadData(this.props)
+ loadData(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.login !== this.props.login) {
- loadData(nextProps)
+ loadData(nextProps);
}
}
handleLoadMoreClick() {
- this.props.loadStarred(this.props.login, true)
+ this.props.loadStarred(this.props.login, true);
}
- renderRepo([ repo, owner ]) {
+ renderRepo([repo, owner]) {
return (
- )
+ owner={owner}
+ key={repo.fullName}
+ />
+ );
}
render() {
- const { user, login } = this.props
+ const { user, login } = this.props;
if (!user) {
- return Loading {login}’s profile...
+ return Loading {login}’s profile... ;
}
- const { starredRepos, starredRepoOwners, starredPagination } = this.props
+ const { starredRepos, starredRepoOwners, starredPagination } = this.props;
return (
+ items={zip(starredRepos, starredRepoOwners)}
+ onLoadMoreClick={this.handleLoadMoreClick}
+ loadingLabel={`Loading ${login}’s starred...`}
+ {...starredPagination}
+ />
- )
+ );
}
}
@@ -69,30 +71,30 @@ UserPage.propTypes = {
starredRepos: PropTypes.array.isRequired,
starredRepoOwners: PropTypes.array.isRequired,
loadUser: PropTypes.func.isRequired,
- loadStarred: PropTypes.func.isRequired
-}
+ loadStarred: PropTypes.func.isRequired,
+};
function mapStateToProps(state, ownProps) {
- const { login } = ownProps.params
+ const { login } = ownProps.params;
const {
pagination: { starredByUser },
- entities: { users, repos }
- } = state
+ entities: { users, repos },
+ } = state;
- const starredPagination = starredByUser[login] || { ids: [] }
- const starredRepos = starredPagination.ids.map(id => repos[id])
- const starredRepoOwners = starredRepos.map(repo => users[repo.owner])
+ const starredPagination = starredByUser[login] || { ids: [] };
+ const starredRepos = starredPagination.ids.map(id => repos[id]);
+ const starredRepoOwners = starredRepos.map(repo => users[repo.owner]);
return {
login,
starredRepos,
starredRepoOwners,
starredPagination,
- user: users[login]
- }
+ user: users[login],
+ };
}
export default connect(mapStateToProps, {
loadUser,
- loadStarred
-})(UserPage)
+ loadStarred,
+})(UserPage);
diff --git a/examples/real-world/index.js b/examples/real-world/index.js
index aacfee6fb5..bd63cf5e2c 100644
--- a/examples/real-world/index.js
+++ b/examples/real-world/index.js
@@ -1,15 +1,15 @@
-import 'babel-polyfill'
-import React from 'react'
-import { render } from 'react-dom'
-import { browserHistory } from 'react-router'
-import { syncHistoryWithStore } from 'react-router-redux'
-import Root from './containers/Root'
-import configureStore from './store/configureStore'
+import 'babel-polyfill';
+import React from 'react';
+import { render } from 'react-dom';
+import { browserHistory } from 'react-router';
+import { syncHistoryWithStore } from 'react-router-redux';
+import Root from './containers/Root';
+import configureStore from './store/configureStore';
-const store = configureStore()
-const history = syncHistoryWithStore(browserHistory, store)
+const store = configureStore();
+const history = syncHistoryWithStore(browserHistory, store);
render(
,
document.getElementById('root')
-)
+);
diff --git a/examples/real-world/middleware/api.js b/examples/real-world/middleware/api.js
index d7ae44a589..640166e590 100644
--- a/examples/real-world/middleware/api.js
+++ b/examples/real-world/middleware/api.js
@@ -1,45 +1,45 @@
-import { Schema, arrayOf, normalize } from 'normalizr'
-import { camelizeKeys } from 'humps'
-import 'isomorphic-fetch'
+import { Schema, arrayOf, normalize } from 'normalizr';
+import { camelizeKeys } from 'humps';
+import 'isomorphic-fetch';
// Extracts the next page URL from Github API response.
function getNextPageUrl(response) {
- const link = response.headers.get('link')
+ const link = response.headers.get('link');
if (!link) {
- return null
+ return null;
}
- const nextLink = link.split(',').find(s => s.indexOf('rel="next"') > -1)
+ const nextLink = link.split(',').find(s => s.indexOf('rel="next"') > -1);
if (!nextLink) {
- return null
+ return null;
}
- return nextLink.split(';')[0].slice(1, -1)
+ return nextLink.split(';')[0].slice(1, -1);
}
-const API_ROOT = 'https://api.github.com/'
+const API_ROOT = 'https://api.github.com/';
// Fetches an API response and normalizes the result JSON according to schema.
// This makes every API response have the same shape, regardless of how nested it was.
function callApi(endpoint, schema) {
- const fullUrl = (endpoint.indexOf(API_ROOT) === -1) ? API_ROOT + endpoint : endpoint
+ const fullUrl = (endpoint.indexOf(API_ROOT) === -1) ? API_ROOT + endpoint : endpoint;
return fetch(fullUrl)
.then(response =>
response.json().then(json => ({ json, response }))
).then(({ json, response }) => {
if (!response.ok) {
- return Promise.reject(json)
+ return Promise.reject(json);
}
- const camelizedJson = camelizeKeys(json)
- const nextPageUrl = getNextPageUrl(response)
+ const camelizedJson = camelizeKeys(json);
+ const nextPageUrl = getNextPageUrl(response);
return Object.assign({},
normalize(camelizedJson, schema),
{ nextPageUrl }
- )
- })
+ );
+ });
}
// We use this Normalizr schemas to transform API responses from a nested form
@@ -51,73 +51,73 @@ function callApi(endpoint, schema) {
// Read more about Normalizr: https://github.com/gaearon/normalizr
const userSchema = new Schema('users', {
- idAttribute: 'login'
-})
+ idAttribute: 'login',
+});
const repoSchema = new Schema('repos', {
- idAttribute: 'fullName'
-})
+ idAttribute: 'fullName',
+});
repoSchema.define({
- owner: userSchema
-})
+ owner: userSchema,
+});
// Schemas for Github API responses.
export const Schemas = {
USER: userSchema,
USER_ARRAY: arrayOf(userSchema),
REPO: repoSchema,
- REPO_ARRAY: arrayOf(repoSchema)
-}
+ REPO_ARRAY: arrayOf(repoSchema),
+};
// Action key that carries API call info interpreted by this Redux middleware.
-export const CALL_API = Symbol('Call API')
+export const CALL_API = Symbol('Call API');
// A Redux middleware that interprets actions with CALL_API info specified.
// Performs the call and promises when such actions are dispatched.
export default store => next => action => {
- const callAPI = action[CALL_API]
+ const callAPI = action[CALL_API];
if (typeof callAPI === 'undefined') {
- return next(action)
+ return next(action);
}
- let { endpoint } = callAPI
- const { schema, types } = callAPI
+ let { endpoint } = callAPI;
+ const { schema, types } = callAPI;
if (typeof endpoint === 'function') {
- endpoint = endpoint(store.getState())
+ endpoint = endpoint(store.getState());
}
if (typeof endpoint !== 'string') {
- throw new Error('Specify a string endpoint URL.')
+ throw new Error('Specify a string endpoint URL.');
}
if (!schema) {
- throw new Error('Specify one of the exported Schemas.')
+ throw new Error('Specify one of the exported Schemas.');
}
if (!Array.isArray(types) || types.length !== 3) {
- throw new Error('Expected an array of three action types.')
+ throw new Error('Expected an array of three action types.');
}
if (!types.every(type => typeof type === 'string')) {
- throw new Error('Expected action types to be strings.')
+ throw new Error('Expected action types to be strings.');
}
function actionWith(data) {
- const finalAction = Object.assign({}, action, data)
- delete finalAction[CALL_API]
- return finalAction
+ const finalAction = Object.assign({}, action, data);
+ delete finalAction[CALL_API];
+ return finalAction;
}
- const [ requestType, successType, failureType ] = types
- next(actionWith({ type: requestType }))
+ const [requestType, successType, failureType] = types;
+ next(actionWith({ type: requestType }));
return callApi(endpoint, schema).then(
response => next(actionWith({
response,
- type: successType
+ type: successType,
})),
error => next(actionWith({
type: failureType,
- error: error.message || 'Something bad happened'
+ error: error.message || 'Something bad happened',
}))
- )
-}
+ );
+};
diff --git a/examples/real-world/reducers/index.js b/examples/real-world/reducers/index.js
index 8dfda6b88a..706f9e1b7f 100644
--- a/examples/real-world/reducers/index.js
+++ b/examples/real-world/reducers/index.js
@@ -1,29 +1,29 @@
-import * as ActionTypes from '../actions'
-import merge from 'lodash/merge'
-import paginate from './paginate'
-import { routerReducer as routing } from 'react-router-redux'
-import { combineReducers } from 'redux'
+import * as ActionTypes from '../actions';
+import merge from 'lodash/merge';
+import paginate from './paginate';
+import { routerReducer as routing } from 'react-router-redux';
+import { combineReducers } from 'redux';
// Updates an entity cache in response to any action with response.entities.
function entities(state = { users: {}, repos: {} }, action) {
if (action.response && action.response.entities) {
- return merge({}, state, action.response.entities)
+ return merge({}, state, action.response.entities);
}
- return state
+ return state;
}
// Updates error message to notify about the failed fetches.
function errorMessage(state = null, action) {
- const { type, error } = action
+ const { type, error } = action;
if (type === ActionTypes.RESET_ERROR_MESSAGE) {
- return null
+ return null;
} else if (error) {
- return action.error
+ return action.error;
}
- return state
+ return state;
}
// Updates the pagination data for different actions.
@@ -33,24 +33,24 @@ const pagination = combineReducers({
types: [
ActionTypes.STARRED_REQUEST,
ActionTypes.STARRED_SUCCESS,
- ActionTypes.STARRED_FAILURE
- ]
+ ActionTypes.STARRED_FAILURE,
+ ],
}),
stargazersByRepo: paginate({
mapActionToKey: action => action.fullName,
types: [
ActionTypes.STARGAZERS_REQUEST,
ActionTypes.STARGAZERS_SUCCESS,
- ActionTypes.STARGAZERS_FAILURE
- ]
- })
-})
+ ActionTypes.STARGAZERS_FAILURE,
+ ],
+ }),
+});
const rootReducer = combineReducers({
entities,
pagination,
errorMessage,
- routing
-})
+ routing,
+});
-export default rootReducer
+export default rootReducer;
diff --git a/examples/real-world/reducers/paginate.js b/examples/real-world/reducers/paginate.js
index 53d5dcc053..bd8a3b4704 100644
--- a/examples/real-world/reducers/paginate.js
+++ b/examples/real-world/reducers/paginate.js
@@ -1,45 +1,45 @@
-import merge from 'lodash/merge'
-import union from 'lodash/union'
+import merge from 'lodash/merge';
+import union from 'lodash/union';
// Creates a reducer managing pagination, given the action types to handle,
// and a function telling how to extract the key from an action.
export default function paginate({ types, mapActionToKey }) {
if (!Array.isArray(types) || types.length !== 3) {
- throw new Error('Expected types to be an array of three elements.')
+ throw new Error('Expected types to be an array of three elements.');
}
if (!types.every(t => typeof t === 'string')) {
- throw new Error('Expected types to be strings.')
+ throw new Error('Expected types to be strings.');
}
if (typeof mapActionToKey !== 'function') {
- throw new Error('Expected mapActionToKey to be a function.')
+ throw new Error('Expected mapActionToKey to be a function.');
}
- const [ requestType, successType, failureType ] = types
+ const [requestType, successType, failureType] = types;
function updatePagination(state = {
isFetching: false,
nextPageUrl: undefined,
pageCount: 0,
- ids: []
+ ids: [],
}, action) {
switch (action.type) {
case requestType:
return merge({}, state, {
- isFetching: true
- })
+ isFetching: true,
+ });
case successType:
return merge({}, state, {
isFetching: false,
ids: union(state.ids, action.response.result),
nextPageUrl: action.response.nextPageUrl,
- pageCount: state.pageCount + 1
- })
+ pageCount: state.pageCount + 1,
+ });
case failureType:
return merge({}, state, {
- isFetching: false
- })
+ isFetching: false,
+ });
default:
- return state
+ return state;
}
}
@@ -47,16 +47,17 @@ export default function paginate({ types, mapActionToKey }) {
switch (action.type) {
case requestType:
case successType:
- case failureType:
- const key = mapActionToKey(action)
+ case failureType: {
+ const key = mapActionToKey(action);
if (typeof key !== 'string') {
- throw new Error('Expected key to be a string.')
+ throw new Error('Expected key to be a string.');
}
return merge({}, state, {
- [key]: updatePagination(state[key], action)
- })
+ [key]: updatePagination(state[key], action),
+ });
+ }
default:
- return state
+ return state;
}
- }
+ };
}
diff --git a/examples/real-world/routes.js b/examples/real-world/routes.js
index 899ff73f89..46ea6fd1fc 100644
--- a/examples/real-world/routes.js
+++ b/examples/real-world/routes.js
@@ -1,14 +1,12 @@
-import React from 'react'
-import { Route } from 'react-router'
-import App from './containers/App'
-import UserPage from './containers/UserPage'
-import RepoPage from './containers/RepoPage'
+import React from 'react';
+import { Route } from 'react-router';
+import App from './containers/App';
+import UserPage from './containers/UserPage';
+import RepoPage from './containers/RepoPage';
export default (
-
-
+
+
-)
+);
diff --git a/examples/real-world/store/configureStore.dev.js b/examples/real-world/store/configureStore.dev.js
index c081a7b347..4763fb1e98 100644
--- a/examples/real-world/store/configureStore.dev.js
+++ b/examples/real-world/store/configureStore.dev.js
@@ -1,9 +1,9 @@
-import { createStore, applyMiddleware, compose } from 'redux'
-import thunk from 'redux-thunk'
-import createLogger from 'redux-logger'
-import api from '../middleware/api'
-import rootReducer from '../reducers'
-import DevTools from '../containers/DevTools'
+import { createStore, applyMiddleware, compose } from 'redux';
+import thunk from 'redux-thunk';
+import createLogger from 'redux-logger';
+import api from '../middleware/api';
+import rootReducer from '../reducers';
+import DevTools from '../containers/DevTools';
export default function configureStore(initialState) {
const store = createStore(
@@ -13,15 +13,15 @@ export default function configureStore(initialState) {
applyMiddleware(thunk, api, createLogger()),
DevTools.instrument()
)
- )
+ );
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
- const nextRootReducer = require('../reducers').default
- store.replaceReducer(nextRootReducer)
- })
+ const nextRootReducer = require('../reducers').default;
+ store.replaceReducer(nextRootReducer);
+ });
}
- return store
+ return store;
}
diff --git a/examples/real-world/store/configureStore.js b/examples/real-world/store/configureStore.js
index a4c9e7ad42..78c9ea1fdc 100644
--- a/examples/real-world/store/configureStore.js
+++ b/examples/real-world/store/configureStore.js
@@ -1,5 +1,5 @@
if (process.env.NODE_ENV === 'production') {
- module.exports = require('./configureStore.prod')
+ module.exports = require('./configureStore.prod');
} else {
- module.exports = require('./configureStore.dev')
+ module.exports = require('./configureStore.dev');
}
diff --git a/examples/real-world/store/configureStore.prod.js b/examples/real-world/store/configureStore.prod.js
index 3a9b853caf..e5b673ab24 100644
--- a/examples/real-world/store/configureStore.prod.js
+++ b/examples/real-world/store/configureStore.prod.js
@@ -1,12 +1,12 @@
-import { createStore, applyMiddleware } from 'redux'
-import thunk from 'redux-thunk'
-import api from '../middleware/api'
-import rootReducer from '../reducers'
+import { createStore, applyMiddleware } from 'redux';
+import thunk from 'redux-thunk';
+import api from '../middleware/api';
+import rootReducer from '../reducers';
export default function configureStore(initialState) {
return createStore(
rootReducer,
initialState,
applyMiddleware(thunk, api)
- )
+ );
}
diff --git a/examples/shopping-cart/actions/index.js b/examples/shopping-cart/actions/index.js
index 5031fce707..701ff3c506 100644
--- a/examples/shopping-cart/actions/index.js
+++ b/examples/shopping-cart/actions/index.js
@@ -1,50 +1,50 @@
-import shop from '../api/shop'
-import * as types from '../constants/ActionTypes'
+import shop from '../api/shop';
+import * as types from '../constants/ActionTypes';
function receiveProducts(products) {
return {
type: types.RECEIVE_PRODUCTS,
- products: products
- }
+ products: products,
+ };
}
export function getAllProducts() {
return dispatch => {
shop.getProducts(products => {
- dispatch(receiveProducts(products))
- })
- }
+ dispatch(receiveProducts(products));
+ });
+ };
}
function addToCartUnsafe(productId) {
return {
type: types.ADD_TO_CART,
- productId
- }
+ productId,
+ };
}
export function addToCart(productId) {
return (dispatch, getState) => {
if (getState().products.byId[productId].inventory > 0) {
- dispatch(addToCartUnsafe(productId))
+ dispatch(addToCartUnsafe(productId));
}
- }
+ };
}
export function checkout(products) {
return (dispatch, getState) => {
- const cart = getState().cart
+ const cart = getState().cart;
dispatch({
- type: types.CHECKOUT_REQUEST
- })
+ type: types.CHECKOUT_REQUEST,
+ });
shop.buyProducts(products, () => {
dispatch({
type: types.CHECKOUT_SUCCESS,
- cart
- })
+ cart,
+ });
// Replace the line above with line below to rollback on failure:
// dispatch({ type: types.CHECKOUT_FAILURE, cart })
- })
- }
+ });
+ };
}
diff --git a/examples/shopping-cart/api/shop.js b/examples/shopping-cart/api/shop.js
index def5958a1c..c9c32481f8 100644
--- a/examples/shopping-cart/api/shop.js
+++ b/examples/shopping-cart/api/shop.js
@@ -1,16 +1,16 @@
/**
* Mocking client-server processing
*/
-import _products from './products.json'
+import _products from './products.json';
-const TIMEOUT = 100
+const TIMEOUT = 100;
export default {
getProducts(cb, timeout) {
- setTimeout(() => cb(_products), timeout || TIMEOUT)
+ setTimeout(() => cb(_products), timeout || TIMEOUT);
},
buyProducts(payload, cb, timeout) {
- setTimeout(() => cb(), timeout || TIMEOUT)
- }
-}
+ setTimeout(() => cb(), timeout || TIMEOUT);
+ },
+};
diff --git a/examples/shopping-cart/components/Cart.js b/examples/shopping-cart/components/Cart.js
index 1fc47cedfa..e59e794e51 100644
--- a/examples/shopping-cart/components/Cart.js
+++ b/examples/shopping-cart/components/Cart.js
@@ -1,11 +1,11 @@
-import React, { Component, PropTypes } from 'react'
-import Product from './Product'
+import React, { Component, PropTypes } from 'react';
+import Product from './Product';
export default class Cart extends Component {
render() {
- const { products, total, onCheckoutClicked } = this.props
+ const { products, total, onCheckoutClicked } = this.props;
- const hasProducts = products.length > 0
+ const hasProducts = products.length > 0;
const nodes = !hasProducts ?
Please add some products to cart. :
products.map(product =>
@@ -13,8 +13,9 @@ export default class Cart extends Component {
title={product.title}
price={product.price}
quantity={product.quantity}
- key={product.id}/>
- )
+ key={product.id}
+ />
+ );
return (
@@ -22,16 +23,17 @@ export default class Cart extends Component {
{nodes}
Total: ${total}
+ disabled={hasProducts ? '' : 'disabled'}
+ >
Checkout
- )
+ );
}
}
Cart.propTypes = {
products: PropTypes.array,
total: PropTypes.string,
- onCheckoutClicked: PropTypes.func
-}
+ onCheckoutClicked: PropTypes.func,
+};
diff --git a/examples/shopping-cart/components/Product.js b/examples/shopping-cart/components/Product.js
index dfa257b7e5..e766050bd4 100644
--- a/examples/shopping-cart/components/Product.js
+++ b/examples/shopping-cart/components/Product.js
@@ -1,14 +1,14 @@
-import React, { Component, PropTypes } from 'react'
+import React, { Component, PropTypes } from 'react';
export default class Product extends Component {
render() {
- const { price, quantity, title } = this.props
- return {title} - ${price} {quantity ? `x ${quantity}` : null}
+ const { price, quantity, title } = this.props;
+ return {title} - ${price} {quantity ? `x ${quantity}` : null}
;
}
}
Product.propTypes = {
price: PropTypes.number,
quantity: PropTypes.number,
- title: PropTypes.string
-}
+ title: PropTypes.string,
+};
diff --git a/examples/shopping-cart/components/ProductItem.js b/examples/shopping-cart/components/ProductItem.js
index c2f58eb235..544edd5f7e 100644
--- a/examples/shopping-cart/components/ProductItem.js
+++ b/examples/shopping-cart/components/ProductItem.js
@@ -1,23 +1,21 @@
-import React, { Component, PropTypes } from 'react'
-import Product from './Product'
+import React, { Component, PropTypes } from 'react';
+import Product from './Product';
export default class ProductItem extends Component {
render() {
- const { product } = this.props
+ const { product } = this.props;
return (
-
-
+
+
0 ? '' : 'disabled'}>
+ disabled={product.inventory > 0 ? '' : 'disabled'}
+ >
{product.inventory > 0 ? 'Add to cart' : 'Sold Out'}
- )
+ );
}
}
@@ -25,7 +23,7 @@ ProductItem.propTypes = {
product: PropTypes.shape({
title: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
- inventory: PropTypes.number.isRequired
+ inventory: PropTypes.number.isRequired,
}).isRequired,
- onAddToCartClicked: PropTypes.func.isRequired
-}
+ onAddToCartClicked: PropTypes.func.isRequired,
+};
diff --git a/examples/shopping-cart/components/ProductsList.js b/examples/shopping-cart/components/ProductsList.js
index 086e529bb8..229a6e501a 100644
--- a/examples/shopping-cart/components/ProductsList.js
+++ b/examples/shopping-cart/components/ProductsList.js
@@ -1,4 +1,4 @@
-import React, { Component, PropTypes } from 'react'
+import React, { Component, PropTypes } from 'react';
export default class ProductsList extends Component {
render() {
@@ -7,11 +7,11 @@ export default class ProductsList extends Component {
{this.props.title}
{this.props.children}
- )
+ );
}
}
ProductsList.propTypes = {
children: PropTypes.node,
- title: PropTypes.string.isRequired
-}
+ title: PropTypes.string.isRequired,
+};
diff --git a/examples/shopping-cart/constants/ActionTypes.js b/examples/shopping-cart/constants/ActionTypes.js
index 6cbabea97c..2f6312297f 100644
--- a/examples/shopping-cart/constants/ActionTypes.js
+++ b/examples/shopping-cart/constants/ActionTypes.js
@@ -1,5 +1,5 @@
-export const ADD_TO_CART = 'ADD_TO_CART'
-export const CHECKOUT_REQUEST = 'CHECKOUT_REQUEST'
-export const CHECKOUT_SUCCESS = 'CHECKOUT_SUCCESS'
-export const CHECKOUT_FAILURE = 'CHECKOUT_FAILURE'
-export const RECEIVE_PRODUCTS = 'RECEIVE_PRODUCTS'
+export const ADD_TO_CART = 'ADD_TO_CART';
+export const CHECKOUT_REQUEST = 'CHECKOUT_REQUEST';
+export const CHECKOUT_SUCCESS = 'CHECKOUT_SUCCESS';
+export const CHECKOUT_FAILURE = 'CHECKOUT_FAILURE';
+export const RECEIVE_PRODUCTS = 'RECEIVE_PRODUCTS';
diff --git a/examples/shopping-cart/containers/App.js b/examples/shopping-cart/containers/App.js
index f19cba3d14..e3eb99248c 100644
--- a/examples/shopping-cart/containers/App.js
+++ b/examples/shopping-cart/containers/App.js
@@ -1,17 +1,17 @@
-import React, { Component } from 'react'
-import ProductsContainer from './ProductsContainer'
-import CartContainer from './CartContainer'
+import React, { Component } from 'react';
+import ProductsContainer from './ProductsContainer';
+import CartContainer from './CartContainer';
export default class App extends Component {
render() {
return (
Shopping Cart Example
-
+
-
+
- )
+ );
}
}
diff --git a/examples/shopping-cart/containers/CartContainer.js b/examples/shopping-cart/containers/CartContainer.js
index 45d5d21ccc..bc911f4847 100644
--- a/examples/shopping-cart/containers/CartContainer.js
+++ b/examples/shopping-cart/containers/CartContainer.js
@@ -1,19 +1,20 @@
-import React, { Component, PropTypes } from 'react'
-import { connect } from 'react-redux'
-import { checkout } from '../actions'
-import { getTotal, getCartProducts } from '../reducers'
-import Cart from '../components/Cart'
+import React, { Component, PropTypes } from 'react';
+import { connect } from 'react-redux';
+import { checkout } from '../actions';
+import { getTotal, getCartProducts } from '../reducers';
+import Cart from '../components/Cart';
class CartContainer extends Component {
render() {
- const { products, total } = this.props
+ const { products, total } = this.props;
return (
this.props.checkout()} />
- )
+ onCheckoutClicked={() => this.props.checkout()}
+ />
+ );
}
}
@@ -22,20 +23,20 @@ CartContainer.propTypes = {
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
- quantity: PropTypes.number.isRequired
+ quantity: PropTypes.number.isRequired,
})).isRequired,
total: PropTypes.string,
- checkout: PropTypes.func.isRequired
-}
+ checkout: PropTypes.func.isRequired,
+};
-const mapStateToProps = (state) => {
- return {
+const mapStateToProps = (state) => (
+ {
products: getCartProducts(state),
- total: getTotal(state)
+ total: getTotal(state),
}
-}
+);
export default connect(
mapStateToProps,
{ checkout }
-)(CartContainer)
+)(CartContainer);
diff --git a/examples/shopping-cart/containers/ProductsContainer.js b/examples/shopping-cart/containers/ProductsContainer.js
index 154982c201..c54660177d 100644
--- a/examples/shopping-cart/containers/ProductsContainer.js
+++ b/examples/shopping-cart/containers/ProductsContainer.js
@@ -1,23 +1,24 @@
-import React, { Component, PropTypes } from 'react'
-import { connect } from 'react-redux'
-import { addToCart } from '../actions'
-import { getVisibleProducts } from '../reducers/products'
-import ProductItem from '../components/ProductItem'
-import ProductsList from '../components/ProductsList'
+import React, { Component, PropTypes } from 'react';
+import { connect } from 'react-redux';
+import { addToCart } from '../actions';
+import { getVisibleProducts } from '../reducers/products';
+import ProductItem from '../components/ProductItem';
+import ProductsList from '../components/ProductsList';
class ProductsContainer extends Component {
render() {
- const { products } = this.props
+ const { products } = this.props;
return (
{products.map(product =>
this.props.addToCart(product.id)} />
+ onAddToCartClicked={() => this.props.addToCart(product.id)}
+ />
)}
- )
+ );
}
}
@@ -26,18 +27,18 @@ ProductsContainer.propTypes = {
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
- inventory: PropTypes.number.isRequired
+ inventory: PropTypes.number.isRequired,
})).isRequired,
- addToCart: PropTypes.func.isRequired
-}
+ addToCart: PropTypes.func.isRequired,
+};
function mapStateToProps(state) {
return {
- products: getVisibleProducts(state.products)
- }
+ products: getVisibleProducts(state.products),
+ };
}
export default connect(
mapStateToProps,
{ addToCart }
-)(ProductsContainer)
+)(ProductsContainer);
diff --git a/examples/shopping-cart/index.js b/examples/shopping-cart/index.js
index 1b475e4714..bd56cca6ab 100644
--- a/examples/shopping-cart/index.js
+++ b/examples/shopping-cart/index.js
@@ -1,28 +1,28 @@
-import 'babel-polyfill'
-import React from 'react'
-import { render } from 'react-dom'
-import { createStore, applyMiddleware } from 'redux'
-import { Provider } from 'react-redux'
-import logger from 'redux-logger'
-import thunk from 'redux-thunk'
-import reducer from './reducers'
-import { getAllProducts } from './actions'
-import App from './containers/App'
+import 'babel-polyfill';
+import React from 'react';
+import { render } from 'react-dom';
+import { createStore, applyMiddleware } from 'redux';
+import { Provider } from 'react-redux';
+import logger from 'redux-logger';
+import thunk from 'redux-thunk';
+import reducer from './reducers';
+import { getAllProducts } from './actions';
+import App from './containers/App';
const middleware = process.env.NODE_ENV === 'production' ?
- [ thunk ] :
- [ thunk, logger() ]
+ [thunk] :
+ [thunk, logger()];
const store = createStore(
reducer,
applyMiddleware(...middleware)
-)
+);
-store.dispatch(getAllProducts())
+store.dispatch(getAllProducts());
render(
,
document.getElementById('root')
-)
+);
diff --git a/examples/shopping-cart/reducers/cart.js b/examples/shopping-cart/reducers/cart.js
index 39725821ef..f4d517e016 100644
--- a/examples/shopping-cart/reducers/cart.js
+++ b/examples/shopping-cart/reducers/cart.js
@@ -1,56 +1,57 @@
import {
ADD_TO_CART,
CHECKOUT_REQUEST,
- CHECKOUT_FAILURE
-} from '../constants/ActionTypes'
+ CHECKOUT_FAILURE,
+} from '../constants/ActionTypes';
const initialState = {
addedIds: [],
- quantityById: {}
-}
+ quantityById: {},
+};
function addedIds(state = initialState.addedIds, action) {
switch (action.type) {
case ADD_TO_CART:
if (state.indexOf(action.productId) !== -1) {
- return state
+ return state;
}
- return [ ...state, action.productId ]
+ return [...state, action.productId];
default:
- return state
+ return state;
}
}
function quantityById(state = initialState.quantityById, action) {
switch (action.type) {
- case ADD_TO_CART:
- const { productId } = action
+ case ADD_TO_CART: {
+ const { productId } = action;
return Object.assign({}, state, {
- [productId]: (state[productId] || 0) + 1
- })
+ [productId]: (state[productId] || 0) + 1,
+ });
+ }
default:
- return state
+ return state;
}
}
export default function cart(state = initialState, action) {
switch (action.type) {
case CHECKOUT_REQUEST:
- return initialState
+ return initialState;
case CHECKOUT_FAILURE:
- return action.cart
+ return action.cart;
default:
return {
addedIds: addedIds(state.addedIds, action),
- quantityById: quantityById(state.quantityById, action)
- }
+ quantityById: quantityById(state.quantityById, action),
+ };
}
}
export function getQuantity(state, productId) {
- return state.quantityById[productId] || 0
+ return state.quantityById[productId] || 0;
}
export function getAddedIds(state) {
- return state.addedIds
+ return state.addedIds;
}
diff --git a/examples/shopping-cart/reducers/index.js b/examples/shopping-cart/reducers/index.js
index 0490144712..18db23ac62 100644
--- a/examples/shopping-cart/reducers/index.js
+++ b/examples/shopping-cart/reducers/index.js
@@ -1,12 +1,12 @@
-import { combineReducers } from 'redux'
-import { default as cart, getQuantity, getAddedIds } from './cart'
-import { default as products, getProduct } from './products'
+import { combineReducers } from 'redux';
+import { default as cart, getQuantity, getAddedIds } from './cart';
+import { default as products, getProduct } from './products';
export function getTotal(state) {
return getAddedIds(state.cart).reduce((total, id) =>
total + getProduct(state.products, id).price * getQuantity(state.cart, id),
0
- ).toFixed(2)
+ ).toFixed(2);
}
export function getCartProducts(state) {
@@ -14,12 +14,12 @@ export function getCartProducts(state) {
{},
getProduct(state.products, id),
{
- quantity: getQuantity(state.cart, id)
+ quantity: getQuantity(state.cart, id),
}
- ))
+ ));
}
export default combineReducers({
cart,
- products
-})
+ products,
+});
diff --git a/examples/shopping-cart/reducers/products.js b/examples/shopping-cart/reducers/products.js
index eee1a0200b..60bfa729c8 100644
--- a/examples/shopping-cart/reducers/products.js
+++ b/examples/shopping-cart/reducers/products.js
@@ -1,14 +1,14 @@
-import { combineReducers } from 'redux'
-import { RECEIVE_PRODUCTS, ADD_TO_CART } from '../constants/ActionTypes'
+import { combineReducers } from 'redux';
+import { RECEIVE_PRODUCTS, ADD_TO_CART } from '../constants/ActionTypes';
function products(state, action) {
switch (action.type) {
case ADD_TO_CART:
return Object.assign({}, state, {
- inventory: state.inventory - 1
- })
+ inventory: state.inventory - 1,
+ });
default:
- return state
+ return state;
}
}
@@ -18,39 +18,40 @@ function byId(state = {}, action) {
return Object.assign({},
state,
action.products.reduce((obj, product) => {
- obj[product.id] = product
- return obj
+ obj[product.id] = product;
+ return obj;
}, {})
- )
- default:
- const { productId } = action
+ );
+ default: {
+ const { productId } = action;
if (productId) {
return Object.assign({}, state, {
- [productId]: products(state[productId], action)
- })
+ [productId]: products(state[productId], action),
+ });
}
- return state
+ return state;
+ }
}
}
function visibleIds(state = [], action) {
switch (action.type) {
case RECEIVE_PRODUCTS:
- return action.products.map(product => product.id)
+ return action.products.map(product => product.id);
default:
- return state
+ return state;
}
}
export default combineReducers({
byId,
- visibleIds
-})
+ visibleIds,
+});
export function getProduct(state, id) {
- return state.byId[id]
+ return state.byId[id];
}
export function getVisibleProducts(state) {
- return state.visibleIds.map(id => getProduct(state, id))
+ return state.visibleIds.map(id => getProduct(state, id));
}
diff --git a/examples/shopping-cart/test/components/Cart.spec.js b/examples/shopping-cart/test/components/Cart.spec.js
index d47e69c22e..cec646b4ae 100644
--- a/examples/shopping-cart/test/components/Cart.spec.js
+++ b/examples/shopping-cart/test/components/Cart.spec.js
@@ -1,43 +1,43 @@
-import expect from 'expect'
-import React from 'react'
-import { shallow } from 'enzyme'
-import Cart from '../../components/Cart'
-import Product from '../../components/Product'
+import expect from 'expect';
+import React from 'react';
+import { shallow } from 'enzyme';
+import Cart from '../../components/Cart';
+import Product from '../../components/Product';
function setup(total, products = []) {
const actions = {
- onCheckoutClicked: expect.createSpy()
- }
+ onCheckoutClicked: expect.createSpy(),
+ };
const component = shallow(
- )
+ );
return {
- component: component,
- actions: actions,
+ component,
+ actions,
button: component.find('button'),
products: component.find(Product),
em: component.find('em'),
- p: component.find('p')
- }
+ p: component.find('p'),
+ };
}
describe('Cart component', () => {
it('should display total', () => {
- const { p } = setup('76')
- expect(p.text()).toMatch(/^Total: \$76/)
- })
+ const { p } = setup('76');
+ expect(p.text()).toMatch(/^Total: \$76/);
+ });
it('should display add some products message', () => {
- const { em } = setup()
- expect(em.text()).toMatch(/^Please add some products to cart/)
- })
+ const { em } = setup();
+ expect(em.text()).toMatch(/^Please add some products to cart/);
+ });
it('should disable button', () => {
- const { button } = setup()
- expect(button.prop('disabled')).toEqual('disabled')
- })
+ const { button } = setup();
+ expect(button.prop('disabled')).toEqual('disabled');
+ });
describe('when given product', () => {
const product = [
@@ -45,30 +45,30 @@ describe('Cart component', () => {
id: 1,
title: 'Product 1',
price: 9.99,
- quantity: 1
- }
- ]
+ quantity: 1,
+ },
+ ];
it('should render products', () => {
- const { products } = setup('9.99', product)
+ const { products } = setup('9.99', product);
const props = {
title: product[0].title,
price: product[0].price,
- quantity: product[0].quantity
- }
+ quantity: product[0].quantity,
+ };
- expect(products.at(0).props()).toEqual(props)
- })
+ expect(products.at(0).props()).toEqual(props);
+ });
it('should not disable button', () => {
- const { button } = setup('9.99', product)
- expect(button.prop('disabled')).toEqual('')
- })
+ const { button } = setup('9.99', product);
+ expect(button.prop('disabled')).toEqual('');
+ });
it('should call action on button click', () => {
- const { button, actions } = setup('9.99', product)
- button.simulate('click')
- expect(actions.onCheckoutClicked).toHaveBeenCalled()
- })
- })
-})
+ const { button, actions } = setup('9.99', product);
+ button.simulate('click');
+ expect(actions.onCheckoutClicked).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/examples/shopping-cart/test/components/Product.spec.js b/examples/shopping-cart/test/components/Product.spec.js
index a8d0deab7a..ed584772d1 100644
--- a/examples/shopping-cart/test/components/Product.spec.js
+++ b/examples/shopping-cart/test/components/Product.spec.js
@@ -1,28 +1,28 @@
-import expect from 'expect'
-import React from 'react'
-import { shallow } from 'enzyme'
-import Product from '../../components/Product'
+import expect from 'expect';
+import React from 'react';
+import { shallow } from 'enzyme';
+import Product from '../../components/Product';
function setup(props) {
const component = shallow(
- )
+ );
return {
- component: component
- }
+ component,
+ };
}
describe('Product component', () => {
it('should render title and price', () => {
- const { component } = setup({ title: 'Test Product', price: 9.99 })
- expect(component.text()).toMatch(/^ Test Product - \$9.99 {2}$/)
- })
+ const { component } = setup({ title: 'Test Product', price: 9.99 });
+ expect(component.text()).toMatch(/^ Test Product - \$9.99 {2}$/);
+ });
describe('when given quantity', () => {
it('should render title, price, and quantity', () => {
- const { component } = setup({ title: 'Test Product', price: 9.99, quantity: 6 })
- expect(component.text()).toMatch(/^ Test Product - \$9.99 x 6 $/)
- })
- })
-})
+ const { component } = setup({ title: 'Test Product', price: 9.99, quantity: 6 });
+ expect(component.text()).toMatch(/^ Test Product - \$9.99 x 6 $/);
+ });
+ });
+});
diff --git a/examples/shopping-cart/test/components/ProductItem.spec.js b/examples/shopping-cart/test/components/ProductItem.spec.js
index 1d960a2e19..59d9cdfbb1 100644
--- a/examples/shopping-cart/test/components/ProductItem.spec.js
+++ b/examples/shopping-cart/test/components/ProductItem.spec.js
@@ -1,71 +1,71 @@
-import expect from 'expect'
-import React from 'react'
-import { shallow } from 'enzyme'
-import Product from '../../components/Product'
-import ProductItem from '../../components/ProductItem'
+import expect from 'expect';
+import React from 'react';
+import { shallow } from 'enzyme';
+import Product from '../../components/Product';
+import ProductItem from '../../components/ProductItem';
function setup(product) {
const actions = {
- onAddToCartClicked: expect.createSpy()
- }
+ onAddToCartClicked: expect.createSpy(),
+ };
const component = shallow(
- )
+ );
return {
- component: component,
- actions: actions,
+ component,
+ actions,
button: component.find('button'),
- product: component.find(Product)
- }
+ product: component.find(Product),
+ };
}
-let productProps
+let productProps;
describe('ProductItem component', () => {
beforeEach(() => {
productProps = {
title: 'Product 1',
price: 9.99,
- inventory: 6
- }
- })
+ inventory: 6,
+ };
+ });
it('should render product', () => {
- const { product } = setup(productProps)
- expect(product.props()).toEqual({ title: 'Product 1', price: 9.99 })
- })
+ const { product } = setup(productProps);
+ expect(product.props()).toEqual({ title: 'Product 1', price: 9.99 });
+ });
it('should render Add To Cart message', () => {
- const { button } = setup(productProps)
- expect(button.text()).toMatch(/^Add to cart/)
- })
+ const { button } = setup(productProps);
+ expect(button.text()).toMatch(/^Add to cart/);
+ });
it('should not disable button', () => {
- const { button } = setup(productProps)
- expect(button.prop('disabled')).toEqual('')
- })
+ const { button } = setup(productProps);
+ expect(button.prop('disabled')).toEqual('');
+ });
it('should call action on button click', () => {
- const { button, actions } = setup(productProps)
- button.simulate('click')
- expect(actions.onAddToCartClicked).toHaveBeenCalled()
- })
+ const { button, actions } = setup(productProps);
+ button.simulate('click');
+ expect(actions.onAddToCartClicked).toHaveBeenCalled();
+ });
describe('when product inventory is 0', () => {
beforeEach(() => {
- productProps.inventory = 0
- })
+ productProps.inventory = 0;
+ });
it('should render Sold Out message', () => {
- const { button } = setup(productProps)
- expect(button.text()).toMatch(/^Sold Out/)
- })
+ const { button } = setup(productProps);
+ expect(button.text()).toMatch(/^Sold Out/);
+ });
it('should disable button', () => {
- const { button } = setup(productProps)
- expect(button.prop('disabled')).toEqual('disabled')
- })
- })
-})
+ const { button } = setup(productProps);
+ expect(button.prop('disabled')).toEqual('disabled');
+ });
+ });
+});
diff --git a/examples/shopping-cart/test/components/ProductsList.spec.js b/examples/shopping-cart/test/components/ProductsList.spec.js
index 8c34274dfc..f16400b9be 100644
--- a/examples/shopping-cart/test/components/ProductsList.spec.js
+++ b/examples/shopping-cart/test/components/ProductsList.spec.js
@@ -1,28 +1,28 @@
-import expect from 'expect'
-import React from 'react'
-import { shallow } from 'enzyme'
-import ProductsList from '../../components/ProductsList'
+import expect from 'expect';
+import React from 'react';
+import { shallow } from 'enzyme';
+import ProductsList from '../../components/ProductsList';
function setup(props) {
const component = shallow(
{props.children}
- )
+ );
return {
- component: component,
+ component,
children: component.children().at(1),
- h3: component.find('h3')
- }
+ h3: component.find('h3'),
+ };
}
describe('ProductsList component', () => {
it('should render title', () => {
- const { h3 } = setup({ title: 'Test Products' })
- expect(h3.text()).toMatch(/^Test Products$/)
- })
+ const { h3 } = setup({ title: 'Test Products' });
+ expect(h3.text()).toMatch(/^Test Products$/);
+ });
it('should render children', () => {
- const { children } = setup({ title: 'Test Products', children: 'Test Children' })
- expect(children.text()).toMatch(/^Test Children$/)
- })
-})
+ const { children } = setup({ title: 'Test Products', children: 'Test Children' });
+ expect(children.text()).toMatch(/^Test Children$/);
+ });
+});
diff --git a/examples/shopping-cart/test/reducers/cart.spec.js b/examples/shopping-cart/test/reducers/cart.spec.js
index 353e58b832..6522cbbd46 100644
--- a/examples/shopping-cart/test/reducers/cart.spec.js
+++ b/examples/shopping-cart/test/reducers/cart.spec.js
@@ -1,44 +1,44 @@
-import expect from 'expect'
-import cart from '../../reducers/cart'
+import expect from 'expect';
+import cart from '../../reducers/cart';
describe('reducers', () => {
describe('cart', () => {
const initialState = {
addedIds: [],
- quantityById: {}
- }
+ quantityById: {},
+ };
it('should provide the initial state', () => {
- expect(cart(undefined, {})).toEqual(initialState)
- })
+ expect(cart(undefined, {})).toEqual(initialState);
+ });
it('should handle CHECKOUT_REQUEST action', () => {
- expect(cart({}, { type: 'CHECKOUT_REQUEST' })).toEqual(initialState)
- })
+ expect(cart({}, { type: 'CHECKOUT_REQUEST' })).toEqual(initialState);
+ });
it('should handle CHECKOUT_FAILURE action', () => {
- expect(cart({}, { type: 'CHECKOUT_FAILURE', cart: 'cart state' })).toEqual('cart state')
- })
+ expect(cart({}, { type: 'CHECKOUT_FAILURE', cart: 'cart state' })).toEqual('cart state');
+ });
it('should handle ADD_TO_CART action', () => {
expect(cart(initialState, { type: 'ADD_TO_CART', productId: 1 })).toEqual({
- addedIds: [ 1 ],
- quantityById: { 1: 1 }
- })
- })
+ addedIds: [1],
+ quantityById: { 1: 1 },
+ });
+ });
describe('when product is already in cart', () => {
it('should handle ADD_TO_CART action', () => {
const state = {
- addedIds: [ 1, 2 ],
- quantityById: { 1: 1, 2: 1 }
- }
+ addedIds: [1, 2],
+ quantityById: { 1: 1, 2: 1 },
+ };
expect(cart(state, { type: 'ADD_TO_CART', productId: 2 })).toEqual({
- addedIds: [ 1, 2 ],
- quantityById: { 1: 1, 2: 2 }
- })
- })
- })
- })
-})
+ addedIds: [1, 2],
+ quantityById: { 1: 1, 2: 2 },
+ });
+ });
+ });
+ });
+});
diff --git a/examples/shopping-cart/test/reducers/products.spec.js b/examples/shopping-cart/test/reducers/products.spec.js
index c5c8a6f016..e1f5b34651 100644
--- a/examples/shopping-cart/test/reducers/products.spec.js
+++ b/examples/shopping-cart/test/reducers/products.spec.js
@@ -1,5 +1,5 @@
-import expect from 'expect'
-import products from '../../reducers/products'
+import expect from 'expect';
+import products from '../../reducers/products';
describe('reducers', () => {
describe('products', () => {
@@ -9,29 +9,29 @@ describe('reducers', () => {
products: [
{
id: 1,
- title: 'Product 1'
+ title: 'Product 1',
},
{
id: 2,
- title: 'Product 2'
- }
- ]
- }
+ title: 'Product 2',
+ },
+ ],
+ };
expect(products({}, action)).toEqual({
byId: {
1: {
id: 1,
- title: 'Product 1'
+ title: 'Product 1',
},
2: {
id: 2,
- title: 'Product 2'
- }
+ title: 'Product 2',
+ },
},
- visibleIds: [ 1, 2 ]
- })
- })
+ visibleIds: [1, 2],
+ });
+ });
it('should handle ADD_TO_CART action', () => {
const state = {
@@ -39,21 +39,21 @@ describe('reducers', () => {
1: {
id: 1,
title: 'Product 1',
- inventory: 1
- }
- }
- }
+ inventory: 1,
+ },
+ },
+ };
expect(products(state, { type: 'ADD_TO_CART', productId: 1 })).toEqual({
byId: {
1: {
id: 1,
title: 'Product 1',
- inventory: 0
- }
+ inventory: 0,
+ },
},
- visibleIds: []
- })
- })
- })
-})
+ visibleIds: [],
+ });
+ });
+ });
+});
diff --git a/examples/shopping-cart/test/reducers/selectors.spec.js b/examples/shopping-cart/test/reducers/selectors.spec.js
index e07d4e0b56..66b5f85ffd 100644
--- a/examples/shopping-cart/test/reducers/selectors.spec.js
+++ b/examples/shopping-cart/test/reducers/selectors.spec.js
@@ -1,85 +1,85 @@
-import expect from 'expect'
-import { getTotal, getCartProducts } from '../../reducers'
+import expect from 'expect';
+import { getTotal, getCartProducts } from '../../reducers';
describe('selectors', () => {
describe('getTotal', () => {
it('should return price total', () => {
const state = {
cart: {
- addedIds: [ 1, 2, 3 ],
+ addedIds: [1, 2, 3],
quantityById: {
1: 4,
2: 2,
- 3: 1
- }
+ 3: 1,
+ },
},
products: {
byId: {
1: {
id: 1,
- price: 1.99
+ price: 1.99,
},
2: {
id: 1,
- price: 4.99
+ price: 4.99,
},
3: {
id: 1,
- price: 9.99
- }
- }
- }
- }
- expect(getTotal(state)).toBe('27.93')
- })
- })
+ price: 9.99,
+ },
+ },
+ },
+ };
+ expect(getTotal(state)).toBe('27.93');
+ });
+ });
describe('getCartProducts', () => {
it('should return products with quantity', () => {
const state = {
cart: {
- addedIds: [ 1, 2, 3 ],
+ addedIds: [1, 2, 3],
quantityById: {
1: 4,
2: 2,
- 3: 1
- }
+ 3: 1,
+ },
},
products: {
byId: {
1: {
id: 1,
- price: 1.99
+ price: 1.99,
},
2: {
id: 1,
- price: 4.99
+ price: 4.99,
},
3: {
id: 1,
- price: 9.99
- }
- }
- }
- }
+ price: 9.99,
+ },
+ },
+ },
+ };
expect(getCartProducts(state)).toEqual([
{
id: 1,
price: 1.99,
- quantity: 4
+ quantity: 4,
},
{
id: 1,
price: 4.99,
- quantity: 2
+ quantity: 2,
},
{
id: 1,
price: 9.99,
- quantity: 1
- }
- ])
- })
- })
-})
+ quantity: 1,
+ },
+ ]);
+ });
+ });
+});
diff --git a/examples/testAll.js b/examples/testAll.js
index 2667e71ea1..7763f680c3 100644
--- a/examples/testAll.js
+++ b/examples/testAll.js
@@ -2,19 +2,19 @@
* Runs an ordered set of commands within each of the build directories.
*/
-import fs from 'fs'
-import path from 'path'
-import { spawnSync } from 'child_process'
+import fs from 'fs';
+import path from 'path';
+import { spawnSync } from 'child_process';
var exampleDirs = fs.readdirSync(__dirname).filter((file) => {
- return fs.statSync(path.join(__dirname, file)).isDirectory()
-})
+ return fs.statSync(path.join(__dirname, file)).isDirectory();
+});
// Ordering is important here. `npm install` must come first.
var cmdArgs = [
- { cmd: 'npm', args: [ 'install' ] },
- { cmd: 'npm', args: [ 'test' ] }
-]
+ { cmd: 'npm', args: ['install'] },
+ { cmd: 'npm', args: ['test'] }
+];
for (const dir of exampleDirs) {
for (const cmdArg of cmdArgs) {
@@ -22,16 +22,16 @@ for (const dir of exampleDirs) {
const opts = {
cwd: path.join(__dirname, dir),
stdio: 'inherit'
- }
+ };
- let result = {}
+ let result = {};
if (process.platform === 'win32') {
- result = spawnSync(cmdArg.cmd + '.cmd', cmdArg.args, opts)
+ result = spawnSync(cmdArg.cmd + '.cmd', cmdArg.args, opts);
} else {
- result = spawnSync(cmdArg.cmd, cmdArg.args, opts)
+ result = spawnSync(cmdArg.cmd, cmdArg.args, opts);
}
if (result.status !== 0) {
- throw new Error('Building examples exited with non-zero')
+ throw new Error('Building examples exited with non-zero');
}
}
}
diff --git a/examples/todomvc/actions/index.js b/examples/todomvc/actions/index.js
index 2e52a7cf1b..6424722129 100644
--- a/examples/todomvc/actions/index.js
+++ b/examples/todomvc/actions/index.js
@@ -1,25 +1,25 @@
-import * as types from '../constants/ActionTypes'
+import * as types from '../constants/ActionTypes';
export function addTodo(text) {
- return { type: types.ADD_TODO, text }
+ return { type: types.ADD_TODO, text };
}
export function deleteTodo(id) {
- return { type: types.DELETE_TODO, id }
+ return { type: types.DELETE_TODO, id };
}
export function editTodo(id, text) {
- return { type: types.EDIT_TODO, id, text }
+ return { type: types.EDIT_TODO, id, text };
}
export function completeTodo(id) {
- return { type: types.COMPLETE_TODO, id }
+ return { type: types.COMPLETE_TODO, id };
}
export function completeAll() {
- return { type: types.COMPLETE_ALL }
+ return { type: types.COMPLETE_ALL };
}
export function clearCompleted() {
- return { type: types.CLEAR_COMPLETED }
+ return { type: types.CLEAR_COMPLETED };
}
diff --git a/examples/todomvc/components/Footer.js b/examples/todomvc/components/Footer.js
index 8ae9c59983..6d1cfb6824 100644
--- a/examples/todomvc/components/Footer.js
+++ b/examples/todomvc/components/Footer.js
@@ -1,47 +1,47 @@
-import React, { PropTypes, Component } from 'react'
-import classnames from 'classnames'
-import { SHOW_ALL, SHOW_COMPLETED, SHOW_ACTIVE } from '../constants/TodoFilters'
+import React, { PropTypes, Component } from 'react';
+import classnames from 'classnames';
+import { SHOW_ALL, SHOW_COMPLETED, SHOW_ACTIVE } from '../constants/TodoFilters';
const FILTER_TITLES = {
[SHOW_ALL]: 'All',
[SHOW_ACTIVE]: 'Active',
- [SHOW_COMPLETED]: 'Completed'
-}
+ [SHOW_COMPLETED]: 'Completed',
+};
class Footer extends Component {
renderTodoCount() {
- const { activeCount } = this.props
- const itemWord = activeCount === 1 ? 'item' : 'items'
+ const { activeCount } = this.props;
+ const itemWord = activeCount === 1 ? 'item' : 'items';
return (
{activeCount || 'No'} {itemWord} left
- )
+ );
}
renderFilterLink(filter) {
- const title = FILTER_TITLES[filter]
- const { filter: selectedFilter, onShow } = this.props
+ const title = FILTER_TITLES[filter];
+ const { filter: selectedFilter, onShow } = this.props;
return (
onShow(filter)}>
+ style={{ cursor: 'pointer' }}
+ onClick={() => onShow(filter)}
+ >
{title}
- )
+ );
}
renderClearButton() {
- const { completedCount, onClearCompleted } = this.props
+ const { completedCount, onClearCompleted } = this.props;
if (completedCount > 0) {
return (
-
+
Clear completed
- )
+ );
}
}
@@ -50,7 +50,7 @@ class Footer extends Component {
{this.renderTodoCount()}
- {[ SHOW_ALL, SHOW_ACTIVE, SHOW_COMPLETED ].map(filter =>
+ {[SHOW_ALL, SHOW_ACTIVE, SHOW_COMPLETED].map(filter =>
{this.renderFilterLink(filter)}
@@ -58,7 +58,7 @@ class Footer extends Component {
{this.renderClearButton()}
- )
+ );
}
}
@@ -67,7 +67,7 @@ Footer.propTypes = {
activeCount: PropTypes.number.isRequired,
filter: PropTypes.string.isRequired,
onClearCompleted: PropTypes.func.isRequired,
- onShow: PropTypes.func.isRequired
-}
+ onShow: PropTypes.func.isRequired,
+};
-export default Footer
+export default Footer;
diff --git a/examples/todomvc/components/Header.js b/examples/todomvc/components/Header.js
index aeb8303819..6390b10dc7 100644
--- a/examples/todomvc/components/Header.js
+++ b/examples/todomvc/components/Header.js
@@ -1,10 +1,10 @@
-import React, { PropTypes, Component } from 'react'
-import TodoTextInput from './TodoTextInput'
+import React, { PropTypes, Component } from 'react';
+import TodoTextInput from './TodoTextInput';
class Header extends Component {
handleSave(text) {
if (text.length !== 0) {
- this.props.addTodo(text)
+ this.props.addTodo(text);
}
}
@@ -13,15 +13,16 @@ class Header extends Component {
todos
+ onSave={this.handleSave.bind(this)}
+ placeholder="What needs to be done?"
+ />
- )
+ );
}
}
Header.propTypes = {
- addTodo: PropTypes.func.isRequired
-}
+ addTodo: PropTypes.func.isRequired,
+};
-export default Header
+export default Header;
diff --git a/examples/todomvc/components/MainSection.js b/examples/todomvc/components/MainSection.js
index f5c2804010..5d38cbf41d 100644
--- a/examples/todomvc/components/MainSection.js
+++ b/examples/todomvc/components/MainSection.js
@@ -1,65 +1,69 @@
-import React, { Component, PropTypes } from 'react'
-import TodoItem from './TodoItem'
-import Footer from './Footer'
-import { SHOW_ALL, SHOW_COMPLETED, SHOW_ACTIVE } from '../constants/TodoFilters'
+import React, { Component, PropTypes } from 'react';
+import TodoItem from './TodoItem';
+import Footer from './Footer';
+import { SHOW_ALL, SHOW_COMPLETED, SHOW_ACTIVE } from '../constants/TodoFilters';
const TODO_FILTERS = {
[SHOW_ALL]: () => true,
[SHOW_ACTIVE]: todo => !todo.completed,
- [SHOW_COMPLETED]: todo => todo.completed
-}
+ [SHOW_COMPLETED]: todo => todo.completed,
+};
class MainSection extends Component {
constructor(props, context) {
- super(props, context)
- this.state = { filter: SHOW_ALL }
+ super(props, context);
+ this.state = { filter: SHOW_ALL };
+ this.handleClearCompleted = this.handleClearCompleted.bind(this);
+ this.handleShow = this.handleShow.bind(this);
}
handleClearCompleted() {
- this.props.actions.clearCompleted()
+ this.props.actions.clearCompleted();
}
handleShow(filter) {
- this.setState({ filter })
+ this.setState({ filter });
}
renderToggleAll(completedCount) {
- const { todos, actions } = this.props
+ const { todos, actions } = this.props;
if (todos.length > 0) {
return (
- )
+ type="checkbox"
+ checked={completedCount === todos.length}
+ onChange={actions.completeAll}
+ />
+ );
}
}
renderFooter(completedCount) {
- const { todos } = this.props
- const { filter } = this.state
- const activeCount = todos.length - completedCount
+ const { todos } = this.props;
+ const { filter } = this.state;
+ const activeCount = todos.length - completedCount;
if (todos.length) {
return (
- )
+ activeCount={activeCount}
+ filter={filter}
+ onClearCompleted={this.handleClearCompleted}
+ onShow={this.handleShow}
+ />
+ );
}
}
render() {
- const { todos, actions } = this.props
- const { filter } = this.state
+ const { todos, actions } = this.props;
+ const { filter } = this.state;
- const filteredTodos = todos.filter(TODO_FILTERS[filter])
- const completedCount = todos.reduce((count, todo) =>
+ const filteredTodos = todos.filter(TODO_FILTERS[filter]);
+ const completedCount = todos.reduce((count, todo) => (
todo.completed ? count + 1 : count,
0
- )
+ ));
return (
@@ -71,13 +75,13 @@ class MainSection extends Component {
{this.renderFooter(completedCount)}
- )
+ );
}
}
MainSection.propTypes = {
todos: PropTypes.array.isRequired,
- actions: PropTypes.object.isRequired
-}
+ actions: PropTypes.object.isRequired,
+};
-export default MainSection
+export default MainSection;
diff --git a/examples/todomvc/components/TodoItem.js b/examples/todomvc/components/TodoItem.js
index a892951842..ae6d9242f1 100644
--- a/examples/todomvc/components/TodoItem.js
+++ b/examples/todomvc/components/TodoItem.js
@@ -1,62 +1,66 @@
-import React, { Component, PropTypes } from 'react'
-import classnames from 'classnames'
-import TodoTextInput from './TodoTextInput'
+import React, { Component, PropTypes } from 'react';
+import classnames from 'classnames';
+import TodoTextInput from './TodoTextInput';
class TodoItem extends Component {
constructor(props, context) {
- super(props, context)
+ super(props, context);
this.state = {
- editing: false
- }
+ editing: false,
+ };
+ this.handleDoubleClick = this.handleDoubleClick.bind(this);
}
handleDoubleClick() {
- this.setState({ editing: true })
+ this.setState({ editing: true });
}
handleSave(id, text) {
if (text.length === 0) {
- this.props.deleteTodo(id)
+ this.props.deleteTodo(id);
} else {
- this.props.editTodo(id, text)
+ this.props.editTodo(id, text);
}
- this.setState({ editing: false })
+ this.setState({ editing: false });
}
render() {
- const { todo, completeTodo, deleteTodo } = this.props
+ const { todo, completeTodo, deleteTodo } = this.props;
- let element
+ let element;
if (this.state.editing) {
element = (
this.handleSave(todo.id, text)} />
- )
+ editing={this.state.editing}
+ onSave={(text) => this.handleSave(todo.id, text)}
+ />
+ );
} else {
element = (
completeTodo(todo.id)} />
-
+ type="checkbox"
+ checked={todo.completed}
+ onChange={() => completeTodo(todo.id)}
+ />
+
{todo.text}
- deleteTodo(todo.id)} />
+ deleteTodo(todo.id)} />
- )
+ );
}
return (
-
+
{element}
- )
+ );
}
}
@@ -64,7 +68,7 @@ TodoItem.propTypes = {
todo: PropTypes.object.isRequired,
editTodo: PropTypes.func.isRequired,
deleteTodo: PropTypes.func.isRequired,
- completeTodo: PropTypes.func.isRequired
-}
+ completeTodo: PropTypes.func.isRequired,
+};
-export default TodoItem
+export default TodoItem;
diff --git a/examples/todomvc/components/TodoTextInput.js b/examples/todomvc/components/TodoTextInput.js
index bfdbf7d609..f0e69c26d2 100644
--- a/examples/todomvc/components/TodoTextInput.js
+++ b/examples/todomvc/components/TodoTextInput.js
@@ -1,31 +1,34 @@
-import React, { Component, PropTypes } from 'react'
-import classnames from 'classnames'
+import React, { Component, PropTypes } from 'react';
+import classnames from 'classnames';
class TodoTextInput extends Component {
constructor(props, context) {
- super(props, context)
+ super(props, context);
this.state = {
- text: this.props.text || ''
- }
+ text: this.props.text || '',
+ };
+ this.handleBlur = this.handleBlur.bind(this);
+ this.handleChange = this.handleChange.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
- const text = e.target.value.trim()
+ const text = e.target.value.trim();
if (e.which === 13) {
- this.props.onSave(text)
+ this.props.onSave(text);
if (this.props.newTodo) {
- this.setState({ text: '' })
+ this.setState({ text: '' });
}
}
}
handleChange(e) {
- this.setState({ text: e.target.value })
+ this.setState({ text: e.target.value });
}
handleBlur(e) {
if (!this.props.newTodo) {
- this.props.onSave(e.target.value)
+ this.props.onSave(e.target.value);
}
}
@@ -34,16 +37,17 @@ class TodoTextInput extends Component {
- )
+ onBlur={this.handleBlur}
+ onChange={this.handleChange}
+ onKeyDown={this.handleSubmit}
+ />
+ );
}
}
@@ -52,7 +56,7 @@ TodoTextInput.propTypes = {
text: PropTypes.string,
placeholder: PropTypes.string,
editing: PropTypes.bool,
- newTodo: PropTypes.bool
-}
+ newTodo: PropTypes.bool,
+};
-export default TodoTextInput
+export default TodoTextInput;
diff --git a/examples/todomvc/constants/ActionTypes.js b/examples/todomvc/constants/ActionTypes.js
index a7cdd02d93..6b9166e807 100644
--- a/examples/todomvc/constants/ActionTypes.js
+++ b/examples/todomvc/constants/ActionTypes.js
@@ -1,6 +1,6 @@
-export const ADD_TODO = 'ADD_TODO'
-export const DELETE_TODO = 'DELETE_TODO'
-export const EDIT_TODO = 'EDIT_TODO'
-export const COMPLETE_TODO = 'COMPLETE_TODO'
-export const COMPLETE_ALL = 'COMPLETE_ALL'
-export const CLEAR_COMPLETED = 'CLEAR_COMPLETED'
+export const ADD_TODO = 'ADD_TODO';
+export const DELETE_TODO = 'DELETE_TODO';
+export const EDIT_TODO = 'EDIT_TODO';
+export const COMPLETE_TODO = 'COMPLETE_TODO';
+export const COMPLETE_ALL = 'COMPLETE_ALL';
+export const CLEAR_COMPLETED = 'CLEAR_COMPLETED';
diff --git a/examples/todomvc/constants/TodoFilters.js b/examples/todomvc/constants/TodoFilters.js
index 7268785d56..9da7f831c3 100644
--- a/examples/todomvc/constants/TodoFilters.js
+++ b/examples/todomvc/constants/TodoFilters.js
@@ -1,3 +1,3 @@
-export const SHOW_ALL = 'show_all'
-export const SHOW_COMPLETED = 'show_completed'
-export const SHOW_ACTIVE = 'show_active'
+export const SHOW_ALL = 'show_all';
+export const SHOW_COMPLETED = 'show_completed';
+export const SHOW_ACTIVE = 'show_active';
diff --git a/examples/todomvc/containers/App.js b/examples/todomvc/containers/App.js
index dffbb915ca..28392fc323 100644
--- a/examples/todomvc/containers/App.js
+++ b/examples/todomvc/containers/App.js
@@ -1,40 +1,40 @@
-import React, { Component, PropTypes } from 'react'
-import { bindActionCreators } from 'redux'
-import { connect } from 'react-redux'
-import Header from '../components/Header'
-import MainSection from '../components/MainSection'
-import * as TodoActions from '../actions'
+import React, { Component, PropTypes } from 'react';
+import { bindActionCreators } from 'redux';
+import { connect } from 'react-redux';
+import Header from '../components/Header';
+import MainSection from '../components/MainSection';
+import * as TodoActions from '../actions';
class App extends Component {
render() {
- const { todos, actions } = this.props
+ const { todos, actions } = this.props;
return (
- )
+ );
}
}
App.propTypes = {
todos: PropTypes.array.isRequired,
- actions: PropTypes.object.isRequired
-}
+ actions: PropTypes.object.isRequired,
+};
function mapStateToProps(state) {
return {
- todos: state.todos
- }
+ todos: state.todos,
+ };
}
function mapDispatchToProps(dispatch) {
return {
- actions: bindActionCreators(TodoActions, dispatch)
- }
+ actions: bindActionCreators(TodoActions, dispatch),
+ };
}
export default connect(
mapStateToProps,
mapDispatchToProps
-)(App)
+)(App);
diff --git a/examples/todomvc/index.js b/examples/todomvc/index.js
index 988cc99ccd..4f3b96ccde 100644
--- a/examples/todomvc/index.js
+++ b/examples/todomvc/index.js
@@ -1,16 +1,16 @@
-import 'babel-polyfill'
-import React from 'react'
-import { render } from 'react-dom'
-import { Provider } from 'react-redux'
-import App from './containers/App'
-import configureStore from './store/configureStore'
-import 'todomvc-app-css/index.css'
+import 'babel-polyfill';
+import React from 'react';
+import { render } from 'react-dom';
+import { Provider } from 'react-redux';
+import App from './containers/App';
+import configureStore from './store/configureStore';
+import 'todomvc-app-css/index.css';
-const store = configureStore()
+const store = configureStore();
render(
,
document.getElementById('root')
-)
+);
diff --git a/examples/todomvc/reducers/index.js b/examples/todomvc/reducers/index.js
index a94ace36b9..e59c909e3c 100644
--- a/examples/todomvc/reducers/index.js
+++ b/examples/todomvc/reducers/index.js
@@ -1,8 +1,8 @@
-import { combineReducers } from 'redux'
-import todos from './todos'
+import { combineReducers } from 'redux';
+import todos from './todos';
const rootReducer = combineReducers({
- todos
-})
+ todos,
+});
-export default rootReducer
+export default rootReducer;
diff --git a/examples/todomvc/reducers/todos.js b/examples/todomvc/reducers/todos.js
index 1655999bb6..0e028a7d38 100644
--- a/examples/todomvc/reducers/todos.js
+++ b/examples/todomvc/reducers/todos.js
@@ -1,12 +1,15 @@
-import { ADD_TODO, DELETE_TODO, EDIT_TODO, COMPLETE_TODO, COMPLETE_ALL, CLEAR_COMPLETED } from '../constants/ActionTypes'
+import {
+ ADD_TODO, DELETE_TODO, EDIT_TODO,
+ COMPLETE_TODO, COMPLETE_ALL, CLEAR_COMPLETED,
+} from '../constants/ActionTypes';
const initialState = [
{
text: 'Use Redux',
completed: false,
- id: 0
- }
-]
+ id: 0,
+ },
+];
export default function todos(state = initialState, action) {
switch (action.type) {
@@ -15,40 +18,41 @@ export default function todos(state = initialState, action) {
{
id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
completed: false,
- text: action.text
- },
- ...state
- ]
+ text: action.text,
+ },
+ ...state,
+ ];
case DELETE_TODO:
return state.filter(todo =>
todo.id !== action.id
- )
+ );
case EDIT_TODO:
- return state.map(todo =>
+ return state.map(todo => (
todo.id === action.id ?
Object.assign({}, todo, { text: action.text }) :
todo
- )
+ ));
case COMPLETE_TODO:
- return state.map(todo =>
+ return state.map(todo => (
todo.id === action.id ?
Object.assign({}, todo, { completed: !todo.completed }) :
todo
- )
+ ));
- case COMPLETE_ALL:
- const areAllMarked = state.every(todo => todo.completed)
+ case COMPLETE_ALL: {
+ const areAllMarked = state.every(todo => todo.completed);
return state.map(todo => Object.assign({}, todo, {
- completed: !areAllMarked
- }))
+ completed: !areAllMarked,
+ }));
+ }
case CLEAR_COMPLETED:
- return state.filter(todo => todo.completed === false)
+ return state.filter(todo => todo.completed === false);
default:
- return state
+ return state;
}
}
diff --git a/examples/todomvc/store/configureStore.js b/examples/todomvc/store/configureStore.js
index 900708b6fa..b764e03cef 100644
--- a/examples/todomvc/store/configureStore.js
+++ b/examples/todomvc/store/configureStore.js
@@ -1,16 +1,16 @@
-import { createStore } from 'redux'
-import rootReducer from '../reducers'
+import { createStore } from 'redux';
+import rootReducer from '../reducers';
export default function configureStore(initialState) {
- const store = createStore(rootReducer, initialState)
+ const store = createStore(rootReducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
- const nextReducer = require('../reducers').default
- store.replaceReducer(nextReducer)
- })
+ const nextReducer = require('../reducers').default;
+ store.replaceReducer(nextReducer);
+ });
}
- return store
+ return store;
}
diff --git a/examples/todomvc/test/actions/todos.spec.js b/examples/todomvc/test/actions/todos.spec.js
index 0feb331fbf..554fe7499f 100644
--- a/examples/todomvc/test/actions/todos.spec.js
+++ b/examples/todomvc/test/actions/todos.spec.js
@@ -1,46 +1,46 @@
-import expect from 'expect'
-import * as types from '../../constants/ActionTypes'
-import * as actions from '../../actions'
+import expect from 'expect';
+import * as types from '../../constants/ActionTypes';
+import * as actions from '../../actions';
describe('todo actions', () => {
it('addTodo should create ADD_TODO action', () => {
expect(actions.addTodo('Use Redux')).toEqual({
type: types.ADD_TODO,
- text: 'Use Redux'
- })
- })
+ text: 'Use Redux',
+ });
+ });
it('deleteTodo should create DELETE_TODO action', () => {
expect(actions.deleteTodo(1)).toEqual({
type: types.DELETE_TODO,
- id: 1
- })
- })
+ id: 1,
+ });
+ });
it('editTodo should create EDIT_TODO action', () => {
expect(actions.editTodo(1, 'Use Redux everywhere')).toEqual({
type: types.EDIT_TODO,
id: 1,
- text: 'Use Redux everywhere'
- })
- })
+ text: 'Use Redux everywhere',
+ });
+ });
it('completeTodo should create COMPLETE_TODO action', () => {
expect(actions.completeTodo(1)).toEqual({
type: types.COMPLETE_TODO,
- id: 1
- })
- })
+ id: 1,
+ });
+ });
it('completeAll should create COMPLETE_ALL action', () => {
expect(actions.completeAll()).toEqual({
- type: types.COMPLETE_ALL
- })
- })
+ type: types.COMPLETE_ALL,
+ });
+ });
it('clearCompleted should create CLEAR_COMPLETED action', () => {
expect(actions.clearCompleted()).toEqual({
- type: types.CLEAR_COMPLETED
- })
- })
-})
+ type: types.CLEAR_COMPLETED,
+ });
+ });
+});
diff --git a/examples/todomvc/test/components/Footer.spec.js b/examples/todomvc/test/components/Footer.spec.js
index b482a2d343..6b43d290c0 100644
--- a/examples/todomvc/test/components/Footer.spec.js
+++ b/examples/todomvc/test/components/Footer.spec.js
@@ -1,8 +1,8 @@
-import expect from 'expect'
-import React from 'react'
-import TestUtils from 'react-addons-test-utils'
-import Footer from '../../components/Footer'
-import { SHOW_ALL, SHOW_ACTIVE } from '../../constants/TodoFilters'
+import expect from 'expect';
+import React from 'react';
+import TestUtils from 'react-addons-test-utils';
+import Footer from '../../components/Footer';
+import { SHOW_ALL, SHOW_ACTIVE } from '../../constants/TodoFilters';
function setup(propOverrides) {
const props = Object.assign({
@@ -10,93 +10,93 @@ function setup(propOverrides) {
activeCount: 0,
filter: SHOW_ALL,
onClearCompleted: expect.createSpy(),
- onShow: expect.createSpy()
- }, propOverrides)
+ onShow: expect.createSpy(),
+ }, propOverrides);
- const renderer = TestUtils.createRenderer()
- renderer.render()
- const output = renderer.getRenderOutput()
+ const renderer = TestUtils.createRenderer();
+ renderer.render();
+ const output = renderer.getRenderOutput();
return {
- props: props,
- output: output
- }
+ props,
+ output,
+ };
}
function getTextContent(elem) {
const children = Array.isArray(elem.props.children) ?
- elem.props.children : [ elem.props.children ]
+ elem.props.children : [elem.props.children];
- return children.reduce(function concatText(out, child) {
+ return children.reduce((out, child) => {
// Children are either elements or text strings
- return out + (child.props ? getTextContent(child) : child)
- }, '')
+ return out + (child.props ? getTextContent(child) : child);
+ }, '');
}
describe('components', () => {
describe('Footer', () => {
it('should render container', () => {
- const { output } = setup()
- expect(output.type).toBe('footer')
- expect(output.props.className).toBe('footer')
- })
+ const { output } = setup();
+ expect(output.type).toBe('footer');
+ expect(output.props.className).toBe('footer');
+ });
it('should display active count when 0', () => {
- const { output } = setup({ activeCount: 0 })
- const [ count ] = output.props.children
- expect(getTextContent(count)).toBe('No items left')
- })
+ const { output } = setup({ activeCount: 0 });
+ const [count] = output.props.children;
+ expect(getTextContent(count)).toBe('No items left');
+ });
it('should display active count when above 0', () => {
- const { output } = setup({ activeCount: 1 })
- const [ count ] = output.props.children
- expect(getTextContent(count)).toBe('1 item left')
- })
+ const { output } = setup({ activeCount: 1 });
+ const [count] = output.props.children;
+ expect(getTextContent(count)).toBe('1 item left');
+ });
it('should render filters', () => {
- const { output } = setup()
- const [ , filters ] = output.props.children
- expect(filters.type).toBe('ul')
- expect(filters.props.className).toBe('filters')
- expect(filters.props.children.length).toBe(3)
- filters.props.children.forEach(function checkFilter(filter, i) {
- expect(filter.type).toBe('li')
- const a = filter.props.children
- expect(a.props.className).toBe(i === 0 ? 'selected' : '')
+ const { output } = setup();
+ const [, filters] = output.props.children;
+ expect(filters.type).toBe('ul');
+ expect(filters.props.className).toBe('filters');
+ expect(filters.props.children.length).toBe(3);
+ filters.props.children.forEach((filter, i) => {
+ expect(filter.type).toBe('li');
+ const a = filter.props.children;
+ expect(a.props.className).toBe(i === 0 ? 'selected' : '');
expect(a.props.children).toBe({
0: 'All',
1: 'Active',
- 2: 'Completed'
- }[i])
- })
- })
+ 2: 'Completed',
+ }[i]);
+ });
+ });
it('should call onShow when a filter is clicked', () => {
- const { output, props } = setup()
- const [ , filters ] = output.props.children
- const filterLink = filters.props.children[1].props.children
- filterLink.props.onClick({})
- expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE)
- })
+ const { output, props } = setup();
+ const [, filters] = output.props.children;
+ const filterLink = filters.props.children[1].props.children;
+ filterLink.props.onClick({});
+ expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE);
+ });
it('shouldnt show clear button when no completed todos', () => {
- const { output } = setup({ completedCount: 0 })
- const [ , , clear ] = output.props.children
- expect(clear).toBe(undefined)
- })
+ const { output } = setup({ completedCount: 0 });
+ const [, , clear] = output.props.children;
+ expect(clear).toBe(undefined);
+ });
it('should render clear button when completed todos', () => {
- const { output } = setup({ completedCount: 1 })
- const [ , , clear ] = output.props.children
- expect(clear.type).toBe('button')
- expect(clear.props.children).toBe('Clear completed')
- })
+ const { output } = setup({ completedCount: 1 });
+ const [, , clear] = output.props.children;
+ expect(clear.type).toBe('button');
+ expect(clear.props.children).toBe('Clear completed');
+ });
it('should call onClearCompleted on clear button click', () => {
- const { output, props } = setup({ completedCount: 1 })
- const [ , , clear ] = output.props.children
- clear.props.onClick({})
- expect(props.onClearCompleted).toHaveBeenCalled()
- })
- })
-})
+ const { output, props } = setup({ completedCount: 1 });
+ const [, , clear] = output.props.children;
+ clear.props.onClick({});
+ expect(props.onClearCompleted).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/examples/todomvc/test/components/Header.spec.js b/examples/todomvc/test/components/Header.spec.js
index 474a76886c..d570620390 100644
--- a/examples/todomvc/test/components/Header.spec.js
+++ b/examples/todomvc/test/components/Header.spec.js
@@ -1,50 +1,50 @@
-import expect from 'expect'
-import React from 'react'
-import TestUtils from 'react-addons-test-utils'
-import Header from '../../components/Header'
-import TodoTextInput from '../../components/TodoTextInput'
+import expect from 'expect';
+import React from 'react';
+import TestUtils from 'react-addons-test-utils';
+import Header from '../../components/Header';
+import TodoTextInput from '../../components/TodoTextInput';
function setup() {
const props = {
- addTodo: expect.createSpy()
- }
+ addTodo: expect.createSpy(),
+ };
- const renderer = TestUtils.createRenderer()
- renderer.render()
- const output = renderer.getRenderOutput()
+ const renderer = TestUtils.createRenderer();
+ renderer.render();
+ const output = renderer.getRenderOutput();
return {
- props: props,
- output: output,
- renderer: renderer
- }
+ props,
+ output,
+ renderer,
+ };
}
describe('components', () => {
describe('Header', () => {
it('should render correctly', () => {
- const { output } = setup()
+ const { output } = setup();
- expect(output.type).toBe('header')
- expect(output.props.className).toBe('header')
+ expect(output.type).toBe('header');
+ expect(output.props.className).toBe('header');
- const [ h1, input ] = output.props.children
+ const [h1, input] = output.props.children;
- expect(h1.type).toBe('h1')
- expect(h1.props.children).toBe('todos')
+ expect(h1.type).toBe('h1');
+ expect(h1.props.children).toBe('todos');
- expect(input.type).toBe(TodoTextInput)
- expect(input.props.newTodo).toBe(true)
- expect(input.props.placeholder).toBe('What needs to be done?')
- })
+ expect(input.type).toBe(TodoTextInput);
+ expect(input.props.newTodo).toBe(true);
+ expect(input.props.placeholder).toBe('What needs to be done?');
+ });
it('should call addTodo if length of text is greater than 0', () => {
- const { output, props } = setup()
- const input = output.props.children[1]
- input.props.onSave('')
- expect(props.addTodo.calls.length).toBe(0)
- input.props.onSave('Use Redux')
- expect(props.addTodo.calls.length).toBe(1)
- })
- })
-})
+ const { output, props } = setup();
+ const input = output.props.children[1];
+ input.props.onSave('');
+ expect(props.addTodo.calls.length).toBe(0);
+ input.props.onSave('Use Redux');
+ expect(props.addTodo.calls.length).toBe(1);
+ });
+ });
+});
diff --git a/examples/todomvc/test/components/MainSection.spec.js b/examples/todomvc/test/components/MainSection.spec.js
index e3e980adfd..15856dbd5e 100644
--- a/examples/todomvc/test/components/MainSection.spec.js
+++ b/examples/todomvc/test/components/MainSection.spec.js
@@ -1,10 +1,10 @@
-import expect from 'expect'
-import React from 'react'
-import TestUtils from 'react-addons-test-utils'
-import MainSection from '../../components/MainSection'
-import TodoItem from '../../components/TodoItem'
-import Footer from '../../components/Footer'
-import { SHOW_ALL, SHOW_COMPLETED } from '../../constants/TodoFilters'
+import expect from 'expect';
+import React from 'react';
+import TestUtils from 'react-addons-test-utils';
+import MainSection from '../../components/MainSection';
+import TodoItem from '../../components/TodoItem';
+import Footer from '../../components/Footer';
+import { SHOW_ALL, SHOW_COMPLETED } from '../../constants/TodoFilters';
function setup(propOverrides) {
const props = Object.assign({
@@ -12,119 +12,119 @@ function setup(propOverrides) {
{
text: 'Use Redux',
completed: false,
- id: 0
+ id: 0,
}, {
text: 'Run the tests',
completed: true,
- id: 1
- }
+ id: 1,
+ },
],
actions: {
editTodo: expect.createSpy(),
deleteTodo: expect.createSpy(),
completeTodo: expect.createSpy(),
completeAll: expect.createSpy(),
- clearCompleted: expect.createSpy()
- }
- }, propOverrides)
+ clearCompleted: expect.createSpy(),
+ },
+ }, propOverrides);
- const renderer = TestUtils.createRenderer()
- renderer.render( )
- const output = renderer.getRenderOutput()
+ const renderer = TestUtils.createRenderer();
+ renderer.render( );
+ const output = renderer.getRenderOutput();
return {
- props: props,
- output: output,
- renderer: renderer
- }
+ props,
+ output,
+ renderer,
+ };
}
describe('components', () => {
describe('MainSection', () => {
it('should render container', () => {
- const { output } = setup()
- expect(output.type).toBe('section')
- expect(output.props.className).toBe('main')
- })
+ const { output } = setup();
+ expect(output.type).toBe('section');
+ expect(output.props.className).toBe('main');
+ });
describe('toggle all input', () => {
it('should render', () => {
- const { output } = setup()
- const [ toggle ] = output.props.children
- expect(toggle.type).toBe('input')
- expect(toggle.props.type).toBe('checkbox')
- expect(toggle.props.checked).toBe(false)
- })
+ const { output } = setup();
+ const [toggle] = output.props.children;
+ expect(toggle.type).toBe('input');
+ expect(toggle.props.type).toBe('checkbox');
+ expect(toggle.props.checked).toBe(false);
+ });
it('should be checked if all todos completed', () => {
const { output } = setup({ todos: [
{
text: 'Use Redux',
completed: true,
- id: 0
- }
- ]
- })
- const [ toggle ] = output.props.children
- expect(toggle.props.checked).toBe(true)
- })
+ id: 0,
+ },
+ ],
+ });
+ const [toggle] = output.props.children;
+ expect(toggle.props.checked).toBe(true);
+ });
it('should call completeAll on change', () => {
- const { output, props } = setup()
- const [ toggle ] = output.props.children
- toggle.props.onChange({})
- expect(props.actions.completeAll).toHaveBeenCalled()
- })
- })
+ const { output, props } = setup();
+ const [toggle] = output.props.children;
+ toggle.props.onChange({});
+ expect(props.actions.completeAll).toHaveBeenCalled();
+ });
+ });
describe('footer', () => {
it('should render', () => {
- const { output } = setup()
- const [ , , footer ] = output.props.children
- expect(footer.type).toBe(Footer)
- expect(footer.props.completedCount).toBe(1)
- expect(footer.props.activeCount).toBe(1)
- expect(footer.props.filter).toBe(SHOW_ALL)
- })
+ const { output } = setup();
+ const [, , footer] = output.props.children;
+ expect(footer.type).toBe(Footer);
+ expect(footer.props.completedCount).toBe(1);
+ expect(footer.props.activeCount).toBe(1);
+ expect(footer.props.filter).toBe(SHOW_ALL);
+ });
it('onShow should set the filter', () => {
- const { output, renderer } = setup()
- const [ , , footer ] = output.props.children
- footer.props.onShow(SHOW_COMPLETED)
- const updated = renderer.getRenderOutput()
- const [ , , updatedFooter ] = updated.props.children
- expect(updatedFooter.props.filter).toBe(SHOW_COMPLETED)
- })
+ const { output, renderer } = setup();
+ const [, , footer] = output.props.children;
+ footer.props.onShow(SHOW_COMPLETED);
+ const updated = renderer.getRenderOutput();
+ const [, , updatedFooter] = updated.props.children;
+ expect(updatedFooter.props.filter).toBe(SHOW_COMPLETED);
+ });
it('onClearCompleted should call clearCompleted', () => {
- const { output, props } = setup()
- const [ , , footer ] = output.props.children
- footer.props.onClearCompleted()
- expect(props.actions.clearCompleted).toHaveBeenCalled()
- })
- })
+ const { output, props } = setup();
+ const [, , footer] = output.props.children;
+ footer.props.onClearCompleted();
+ expect(props.actions.clearCompleted).toHaveBeenCalled();
+ });
+ });
describe('todo list', () => {
it('should render', () => {
- const { output, props } = setup()
- const [ , list ] = output.props.children
- expect(list.type).toBe('ul')
- expect(list.props.children.length).toBe(2)
+ const { output, props } = setup();
+ const [, list] = output.props.children;
+ expect(list.type).toBe('ul');
+ expect(list.props.children.length).toBe(2);
list.props.children.forEach((item, i) => {
- expect(item.type).toBe(TodoItem)
- expect(item.props.todo).toBe(props.todos[i])
- })
- })
+ expect(item.type).toBe(TodoItem);
+ expect(item.props.todo).toBe(props.todos[i]);
+ });
+ });
it('should filter items', () => {
- const { output, renderer, props } = setup()
- const [ , , footer ] = output.props.children
- footer.props.onShow(SHOW_COMPLETED)
- const updated = renderer.getRenderOutput()
- const [ , updatedList ] = updated.props.children
- expect(updatedList.props.children.length).toBe(1)
- expect(updatedList.props.children[0].props.todo).toBe(props.todos[1])
- })
- })
- })
-})
+ const { output, renderer, props } = setup();
+ const [, , footer] = output.props.children;
+ footer.props.onShow(SHOW_COMPLETED);
+ const updated = renderer.getRenderOutput();
+ const [, updatedList] = updated.props.children;
+ expect(updatedList.props.children.length).toBe(1);
+ expect(updatedList.props.children[0].props.todo).toBe(props.todos[1]);
+ });
+ });
+ });
+});
diff --git a/examples/todomvc/test/components/TodoItem.spec.js b/examples/todomvc/test/components/TodoItem.spec.js
index abbe22b97a..392ff05731 100644
--- a/examples/todomvc/test/components/TodoItem.spec.js
+++ b/examples/todomvc/test/components/TodoItem.spec.js
@@ -1,120 +1,120 @@
-import expect from 'expect'
-import React from 'react'
-import TestUtils from 'react-addons-test-utils'
-import TodoItem from '../../components/TodoItem'
-import TodoTextInput from '../../components/TodoTextInput'
+import expect from 'expect';
+import React from 'react';
+import TestUtils from 'react-addons-test-utils';
+import TodoItem from '../../components/TodoItem';
+import TodoTextInput from '../../components/TodoTextInput';
-function setup( editing = false ) {
+function setup(editing = false) {
const props = {
todo: {
id: 0,
text: 'Use Redux',
- completed: false
+ completed: false,
},
editTodo: expect.createSpy(),
deleteTodo: expect.createSpy(),
- completeTodo: expect.createSpy()
- }
+ completeTodo: expect.createSpy(),
+ };
- const renderer = TestUtils.createRenderer()
+ const renderer = TestUtils.createRenderer();
renderer.render(
- )
+ );
- let output = renderer.getRenderOutput()
+ let output = renderer.getRenderOutput();
if (editing) {
- const label = output.props.children.props.children[1]
- label.props.onDoubleClick({})
- output = renderer.getRenderOutput()
+ const label = output.props.children.props.children[1];
+ label.props.onDoubleClick({});
+ output = renderer.getRenderOutput();
}
return {
- props: props,
- output: output,
- renderer: renderer
- }
+ props,
+ output,
+ renderer,
+ };
}
describe('components', () => {
describe('TodoItem', () => {
it('initial render', () => {
- const { output } = setup()
+ const { output } = setup();
- expect(output.type).toBe('li')
- expect(output.props.className).toBe('')
+ expect(output.type).toBe('li');
+ expect(output.props.className).toBe('');
- const div = output.props.children
+ const div = output.props.children;
- expect(div.type).toBe('div')
- expect(div.props.className).toBe('view')
+ expect(div.type).toBe('div');
+ expect(div.props.className).toBe('view');
- const [ input, label, button ] = div.props.children
+ const [input, label, button] = div.props.children;
- expect(input.type).toBe('input')
- expect(input.props.checked).toBe(false)
+ expect(input.type).toBe('input');
+ expect(input.props.checked).toBe(false);
- expect(label.type).toBe('label')
- expect(label.props.children).toBe('Use Redux')
+ expect(label.type).toBe('label');
+ expect(label.props.children).toBe('Use Redux');
- expect(button.type).toBe('button')
- expect(button.props.className).toBe('destroy')
- })
+ expect(button.type).toBe('button');
+ expect(button.props.className).toBe('destroy');
+ });
it('input onChange should call completeTodo', () => {
- const { output, props } = setup()
- const input = output.props.children.props.children[0]
- input.props.onChange({})
- expect(props.completeTodo).toHaveBeenCalledWith(0)
- })
+ const { output, props } = setup();
+ const input = output.props.children.props.children[0];
+ input.props.onChange({});
+ expect(props.completeTodo).toHaveBeenCalledWith(0);
+ });
it('button onClick should call deleteTodo', () => {
- const { output, props } = setup()
- const button = output.props.children.props.children[2]
- button.props.onClick({})
- expect(props.deleteTodo).toHaveBeenCalledWith(0)
- })
+ const { output, props } = setup();
+ const button = output.props.children.props.children[2];
+ button.props.onClick({});
+ expect(props.deleteTodo).toHaveBeenCalledWith(0);
+ });
it('label onDoubleClick should put component in edit state', () => {
- const { output, renderer } = setup()
- const label = output.props.children.props.children[1]
- label.props.onDoubleClick({})
- const updated = renderer.getRenderOutput()
- expect(updated.type).toBe('li')
- expect(updated.props.className).toBe('editing')
- })
+ const { output, renderer } = setup();
+ const label = output.props.children.props.children[1];
+ label.props.onDoubleClick({});
+ const updated = renderer.getRenderOutput();
+ expect(updated.type).toBe('li');
+ expect(updated.props.className).toBe('editing');
+ });
it('edit state render', () => {
- const { output } = setup(true)
+ const { output } = setup(true);
- expect(output.type).toBe('li')
- expect(output.props.className).toBe('editing')
+ expect(output.type).toBe('li');
+ expect(output.props.className).toBe('editing');
- const input = output.props.children
- expect(input.type).toBe(TodoTextInput)
- expect(input.props.text).toBe('Use Redux')
- expect(input.props.editing).toBe(true)
- })
+ const input = output.props.children;
+ expect(input.type).toBe(TodoTextInput);
+ expect(input.props.text).toBe('Use Redux');
+ expect(input.props.editing).toBe(true);
+ });
it('TodoTextInput onSave should call editTodo', () => {
- const { output, props } = setup(true)
- output.props.children.props.onSave('Use Redux')
- expect(props.editTodo).toHaveBeenCalledWith(0, 'Use Redux')
- })
+ const { output, props } = setup(true);
+ output.props.children.props.onSave('Use Redux');
+ expect(props.editTodo).toHaveBeenCalledWith(0, 'Use Redux');
+ });
it('TodoTextInput onSave should call deleteTodo if text is empty', () => {
- const { output, props } = setup(true)
- output.props.children.props.onSave('')
- expect(props.deleteTodo).toHaveBeenCalledWith(0)
- })
+ const { output, props } = setup(true);
+ output.props.children.props.onSave('');
+ expect(props.deleteTodo).toHaveBeenCalledWith(0);
+ });
it('TodoTextInput onSave should exit component from edit state', () => {
- const { output, renderer } = setup(true)
- output.props.children.props.onSave('Use Redux')
- const updated = renderer.getRenderOutput()
- expect(updated.type).toBe('li')
- expect(updated.props.className).toBe('')
- })
- })
-})
+ const { output, renderer } = setup(true);
+ output.props.children.props.onSave('Use Redux');
+ const updated = renderer.getRenderOutput();
+ expect(updated.type).toBe('li');
+ expect(updated.props.className).toBe('');
+ });
+ });
+});
diff --git a/examples/todomvc/test/components/TodoTextInput.spec.js b/examples/todomvc/test/components/TodoTextInput.spec.js
index bdcfb6d958..4e487719ba 100644
--- a/examples/todomvc/test/components/TodoTextInput.spec.js
+++ b/examples/todomvc/test/components/TodoTextInput.spec.js
@@ -1,7 +1,7 @@
-import expect from 'expect'
-import React from 'react'
-import TestUtils from 'react-addons-test-utils'
-import TodoTextInput from '../../components/TodoTextInput'
+import expect from 'expect';
+import React from 'react';
+import TestUtils from 'react-addons-test-utils';
+import TodoTextInput from '../../components/TodoTextInput';
function setup(propOverrides) {
const props = Object.assign({
@@ -9,75 +9,75 @@ function setup(propOverrides) {
text: 'Use Redux',
placeholder: 'What needs to be done?',
editing: false,
- newTodo: false
- }, propOverrides)
+ newTodo: false,
+ }, propOverrides);
- const renderer = TestUtils.createRenderer()
+ const renderer = TestUtils.createRenderer();
renderer.render(
- )
+ );
- let output = renderer.getRenderOutput()
+ let output = renderer.getRenderOutput();
- output = renderer.getRenderOutput()
+ output = renderer.getRenderOutput();
return {
- props: props,
- output: output,
- renderer: renderer
- }
+ props,
+ output,
+ renderer,
+ };
}
describe('components', () => {
describe('TodoTextInput', () => {
it('should render correctly', () => {
- const { output } = setup()
- expect(output.props.placeholder).toEqual('What needs to be done?')
- expect(output.props.value).toEqual('Use Redux')
- expect(output.props.className).toEqual('')
- })
+ const { output } = setup();
+ expect(output.props.placeholder).toEqual('What needs to be done?');
+ expect(output.props.value).toEqual('Use Redux');
+ expect(output.props.className).toEqual('');
+ });
it('should render correctly when editing=true', () => {
- const { output } = setup({ editing: true })
- expect(output.props.className).toEqual('edit')
- })
+ const { output } = setup({ editing: true });
+ expect(output.props.className).toEqual('edit');
+ });
it('should render correctly when newTodo=true', () => {
- const { output } = setup({ newTodo: true })
- expect(output.props.className).toEqual('new-todo')
- })
+ const { output } = setup({ newTodo: true });
+ expect(output.props.className).toEqual('new-todo');
+ });
it('should update value on change', () => {
- const { output, renderer } = setup()
- output.props.onChange({ target: { value: 'Use Radox' } })
- const updated = renderer.getRenderOutput()
- expect(updated.props.value).toEqual('Use Radox')
- })
+ const { output, renderer } = setup();
+ output.props.onChange({ target: { value: 'Use Radox' } });
+ const updated = renderer.getRenderOutput();
+ expect(updated.props.value).toEqual('Use Radox');
+ });
it('should call onSave on return key press', () => {
- const { output, props } = setup()
- output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } })
- expect(props.onSave).toHaveBeenCalledWith('Use Redux')
- })
+ const { output, props } = setup();
+ output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } });
+ expect(props.onSave).toHaveBeenCalledWith('Use Redux');
+ });
it('should reset state on return key press if newTodo', () => {
- const { output, renderer } = setup({ newTodo: true })
- output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } })
- const updated = renderer.getRenderOutput()
- expect(updated.props.value).toEqual('')
- })
+ const { output, renderer } = setup({ newTodo: true });
+ output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } });
+ const updated = renderer.getRenderOutput();
+ expect(updated.props.value).toEqual('');
+ });
it('should call onSave on blur', () => {
- const { output, props } = setup()
- output.props.onBlur({ target: { value: 'Use Redux' } })
- expect(props.onSave).toHaveBeenCalledWith('Use Redux')
- })
+ const { output, props } = setup();
+ output.props.onBlur({ target: { value: 'Use Redux' } });
+ expect(props.onSave).toHaveBeenCalledWith('Use Redux');
+ });
it('shouldnt call onSave on blur if newTodo', () => {
- const { output, props } = setup({ newTodo: true })
- output.props.onBlur({ target: { value: 'Use Redux' } })
- expect(props.onSave.calls.length).toBe(0)
- })
- })
-})
+ const { output, props } = setup({ newTodo: true });
+ output.props.onBlur({ target: { value: 'Use Redux' } });
+ expect(props.onSave.calls.length).toBe(0);
+ });
+ });
+});
diff --git a/examples/todomvc/test/reducers/todos.spec.js b/examples/todomvc/test/reducers/todos.spec.js
index c7e887c29d..e579e2104b 100644
--- a/examples/todomvc/test/reducers/todos.spec.js
+++ b/examples/todomvc/test/reducers/todos.spec.js
@@ -1,6 +1,6 @@
-import expect from 'expect'
-import todos from '../../reducers/todos'
-import * as types from '../../constants/ActionTypes'
+import expect from 'expect';
+import todos from '../../reducers/todos';
+import * as types from '../../constants/ActionTypes';
describe('todos reducer', () => {
it('should handle initial state', () => {
@@ -10,79 +10,79 @@ describe('todos reducer', () => {
{
text: 'Use Redux',
completed: false,
- id: 0
- }
- ])
- })
+ id: 0,
+ },
+ ]);
+ });
it('should handle ADD_TODO', () => {
expect(
todos([], {
type: types.ADD_TODO,
- text: 'Run the tests'
+ text: 'Run the tests',
})
).toEqual([
{
text: 'Run the tests',
completed: false,
- id: 0
- }
- ])
+ id: 0,
+ },
+ ]);
expect(
todos([
{
text: 'Use Redux',
completed: false,
- id: 0
- }
+ id: 0,
+ },
], {
type: types.ADD_TODO,
- text: 'Run the tests'
+ text: 'Run the tests',
})
).toEqual([
{
text: 'Run the tests',
completed: false,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
- ])
+ id: 0,
+ },
+ ]);
expect(
todos([
{
text: 'Run the tests',
completed: false,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
+ id: 0,
+ },
], {
type: types.ADD_TODO,
- text: 'Fix the tests'
+ text: 'Fix the tests',
})
).toEqual([
{
text: 'Fix the tests',
completed: false,
- id: 2
+ id: 2,
}, {
text: 'Run the tests',
completed: false,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
- ])
- })
+ id: 0,
+ },
+ ]);
+ });
it('should handle DELETE_TODO', () => {
expect(
@@ -90,24 +90,24 @@ describe('todos reducer', () => {
{
text: 'Run the tests',
completed: false,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
+ id: 0,
+ },
], {
type: types.DELETE_TODO,
- id: 1
+ id: 1,
})
).toEqual([
{
text: 'Use Redux',
completed: false,
- id: 0
- }
- ])
- })
+ id: 0,
+ },
+ ]);
+ });
it('should handle EDIT_TODO', () => {
expect(
@@ -115,29 +115,29 @@ describe('todos reducer', () => {
{
text: 'Run the tests',
completed: false,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
+ id: 0,
+ },
], {
type: types.EDIT_TODO,
text: 'Fix the tests',
- id: 1
+ id: 1,
})
).toEqual([
{
text: 'Fix the tests',
completed: false,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
- ])
- })
+ id: 0,
+ },
+ ]);
+ });
it('should handle COMPLETE_TODO', () => {
expect(
@@ -145,28 +145,28 @@ describe('todos reducer', () => {
{
text: 'Run the tests',
completed: false,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
+ id: 0,
+ },
], {
type: types.COMPLETE_TODO,
- id: 1
+ id: 1,
})
).toEqual([
{
text: 'Run the tests',
completed: true,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
- ])
- })
+ id: 0,
+ },
+ ]);
+ });
it('should handle COMPLETE_ALL', () => {
expect(
@@ -174,26 +174,26 @@ describe('todos reducer', () => {
{
text: 'Run the tests',
completed: true,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
+ id: 0,
+ },
], {
- type: types.COMPLETE_ALL
+ type: types.COMPLETE_ALL,
})
).toEqual([
{
text: 'Run the tests',
completed: true,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: true,
- id: 0
- }
- ])
+ id: 0,
+ },
+ ]);
// Unmark if all todos are currently completed
expect(
@@ -201,27 +201,27 @@ describe('todos reducer', () => {
{
text: 'Run the tests',
completed: true,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: true,
- id: 0
- }
+ id: 0,
+ },
], {
- type: types.COMPLETE_ALL
+ type: types.COMPLETE_ALL,
})
).toEqual([
{
text: 'Run the tests',
completed: false,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
- ])
- })
+ id: 0,
+ },
+ ]);
+ });
it('should handle CLEAR_COMPLETED', () => {
expect(
@@ -229,57 +229,57 @@ describe('todos reducer', () => {
{
text: 'Run the tests',
completed: true,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
+ id: 0,
+ },
], {
- type: types.CLEAR_COMPLETED
+ type: types.CLEAR_COMPLETED,
})
).toEqual([
{
text: 'Use Redux',
completed: false,
- id: 0
- }
- ])
- })
+ id: 0,
+ },
+ ]);
+ });
it('should not generate duplicate ids after CLEAR_COMPLETED', () => {
expect(
[
{
type: types.COMPLETE_TODO,
- id: 0
+ id: 0,
}, {
- type: types.CLEAR_COMPLETED
+ type: types.CLEAR_COMPLETED,
}, {
type: types.ADD_TODO,
- text: 'Write more tests'
- }
+ text: 'Write more tests',
+ },
].reduce(todos, [
{
id: 0,
completed: false,
- text: 'Use Redux'
+ text: 'Use Redux',
}, {
id: 1,
completed: false,
- text: 'Write tests'
- }
+ text: 'Write tests',
+ },
])
).toEqual([
{
text: 'Write more tests',
completed: false,
- id: 2
+ id: 2,
}, {
text: 'Write tests',
completed: false,
- id: 1
- }
- ])
- })
-})
+ id: 1,
+ },
+ ]);
+ });
+});
diff --git a/examples/todomvc/test/setup.js b/examples/todomvc/test/setup.js
index c2e0f0cab2..b4e5ab07bf 100644
--- a/examples/todomvc/test/setup.js
+++ b/examples/todomvc/test/setup.js
@@ -1,5 +1,5 @@
-import { jsdom } from 'jsdom'
+import { jsdom } from 'jsdom';
-global.document = jsdom('')
-global.window = document.defaultView
-global.navigator = global.window.navigator
+global.document = jsdom('');
+global.window = document.defaultView;
+global.navigator = global.window.navigator;
diff --git a/examples/todos-with-undo/actions/index.js b/examples/todos-with-undo/actions/index.js
index f64182ed3f..b68d41a81d 100644
--- a/examples/todos-with-undo/actions/index.js
+++ b/examples/todos-with-undo/actions/index.js
@@ -1,22 +1,22 @@
-let nextTodoId = 0
-export const addTodo = (text) => {
- return {
+let nextTodoId = 0;
+export const addTodo = (text) => (
+ {
type: 'ADD_TODO',
id: nextTodoId++,
- text
+ text,
}
-}
+);
-export const setVisibilityFilter = (filter) => {
- return {
+export const setVisibilityFilter = (filter) => (
+ {
type: 'SET_VISIBILITY_FILTER',
- filter
+ filter,
}
-}
+);
-export const toggleTodo = (id) => {
- return {
+export const toggleTodo = (id) => (
+ {
type: 'TOGGLE_TODO',
- id
+ id,
}
-}
+);
diff --git a/examples/todos-with-undo/components/App.js b/examples/todos-with-undo/components/App.js
index c0122f3655..9586f69b7a 100644
--- a/examples/todos-with-undo/components/App.js
+++ b/examples/todos-with-undo/components/App.js
@@ -1,8 +1,8 @@
-import React from 'react'
-import Footer from './Footer'
-import AddTodo from '../containers/AddTodo'
-import VisibleTodoList from '../containers/VisibleTodoList'
-import UndoRedo from '../containers/UndoRedo'
+import React from 'react';
+import Footer from './Footer';
+import AddTodo from '../containers/AddTodo';
+import VisibleTodoList from '../containers/VisibleTodoList';
+import UndoRedo from '../containers/UndoRedo';
const App = () => (
@@ -11,6 +11,6 @@ const App = () => (
-)
+);
-export default App
+export default App;
diff --git a/examples/todos-with-undo/components/Footer.js b/examples/todos-with-undo/components/Footer.js
index 2d7527e745..839da1271f 100644
--- a/examples/todos-with-undo/components/Footer.js
+++ b/examples/todos-with-undo/components/Footer.js
@@ -1,5 +1,5 @@
-import React from 'react'
-import FilterLink from '../containers/FilterLink'
+import React from 'react';
+import FilterLink from '../containers/FilterLink';
const Footer = () => (
@@ -17,6 +17,6 @@ const Footer = () => (
Completed
-)
+);
-export default Footer
+export default Footer;
diff --git a/examples/todos-with-undo/components/Link.js b/examples/todos-with-undo/components/Link.js
index cb781442b7..71bcabda8a 100644
--- a/examples/todos-with-undo/components/Link.js
+++ b/examples/todos-with-undo/components/Link.js
@@ -1,26 +1,26 @@
-import React, { PropTypes } from 'react'
+import React, { PropTypes } from 'react';
const Link = ({ active, children, onClick }) => {
if (active) {
- return {children}
+ return {children} ;
}
return (
{
- e.preventDefault()
- onClick()
- }}
+ onClick={e => {
+ e.preventDefault();
+ onClick();
+ }}
>
{children}
- )
-}
+ );
+};
Link.propTypes = {
active: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
- onClick: PropTypes.func.isRequired
-}
+ onClick: PropTypes.func.isRequired,
+};
-export default Link
+export default Link;
diff --git a/examples/todos-with-undo/components/Todo.js b/examples/todos-with-undo/components/Todo.js
index 234ba77d11..3a6067187e 100644
--- a/examples/todos-with-undo/components/Todo.js
+++ b/examples/todos-with-undo/components/Todo.js
@@ -1,20 +1,20 @@
-import React, { PropTypes } from 'react'
+import React, { PropTypes } from 'react';
const Todo = ({ onClick, completed, text }) => (
{text}
-)
+);
Todo.propTypes = {
onClick: PropTypes.func.isRequired,
completed: PropTypes.bool.isRequired,
- text: PropTypes.string.isRequired
-}
+ text: PropTypes.string.isRequired,
+};
-export default Todo
+export default Todo;
diff --git a/examples/todos-with-undo/components/TodoList.js b/examples/todos-with-undo/components/TodoList.js
index bcd4b1ef59..dd55e7e8d7 100644
--- a/examples/todos-with-undo/components/TodoList.js
+++ b/examples/todos-with-undo/components/TodoList.js
@@ -1,5 +1,5 @@
-import React, { PropTypes } from 'react'
-import Todo from './Todo'
+import React, { PropTypes } from 'react';
+import Todo from './Todo';
const TodoList = ({ todos, onTodoClick }) => (
@@ -11,15 +11,15 @@ const TodoList = ({ todos, onTodoClick }) => (
/>
)}
-)
+);
TodoList.propTypes = {
todos: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
completed: PropTypes.bool.isRequired,
- text: PropTypes.string.isRequired
+ text: PropTypes.string.isRequired,
}).isRequired).isRequired,
- onTodoClick: PropTypes.func.isRequired
-}
+ onTodoClick: PropTypes.func.isRequired,
+};
-export default TodoList
+export default TodoList;
diff --git a/examples/todos-with-undo/containers/AddTodo.js b/examples/todos-with-undo/containers/AddTodo.js
index 39ad22fdb0..4b2f162acf 100644
--- a/examples/todos-with-undo/containers/AddTodo.js
+++ b/examples/todos-with-undo/containers/AddTodo.js
@@ -1,30 +1,39 @@
-import React from 'react'
-import { connect } from 'react-redux'
-import { addTodo } from '../actions'
+import React, { PropTypes } from 'react';
+import { connect } from 'react-redux';
+import { addTodo } from '../actions';
let AddTodo = ({ dispatch }) => {
- let input
+ let input;
return (
-
- )
-}
-AddTodo = connect()(AddTodo)
+ );
+};
-export default AddTodo
+AddTodo.propTypes = {
+ dispatch: PropTypes.func,
+};
+
+AddTodo = connect()(AddTodo);
+
+export default AddTodo;
diff --git a/examples/todos-with-undo/containers/FilterLink.js b/examples/todos-with-undo/containers/FilterLink.js
index 3ff3a93c8c..f46e241bd9 100644
--- a/examples/todos-with-undo/containers/FilterLink.js
+++ b/examples/todos-with-undo/containers/FilterLink.js
@@ -1,24 +1,24 @@
-import { connect } from 'react-redux'
-import { setVisibilityFilter } from '../actions'
-import Link from '../components/Link'
+import { connect } from 'react-redux';
+import { setVisibilityFilter } from '../actions';
+import Link from '../components/Link';
-const mapStateToProps = (state, ownProps) => {
- return {
- active: ownProps.filter === state.visibilityFilter
+const mapStateToProps = (state, ownProps) => (
+ {
+ active: ownProps.filter === state.visibilityFilter,
}
-}
+);
-const mapDispatchToProps = (dispatch, ownProps) => {
- return {
+const mapDispatchToProps = (dispatch, ownProps) => (
+ {
onClick: () => {
- dispatch(setVisibilityFilter(ownProps.filter))
- }
+ dispatch(setVisibilityFilter(ownProps.filter));
+ },
}
-}
+);
const FilterLink = connect(
mapStateToProps,
mapDispatchToProps
-)(Link)
+)(Link);
-export default FilterLink
+export default FilterLink;
diff --git a/examples/todos-with-undo/containers/UndoRedo.js b/examples/todos-with-undo/containers/UndoRedo.js
index 1b13b16511..a60506382e 100644
--- a/examples/todos-with-undo/containers/UndoRedo.js
+++ b/examples/todos-with-undo/containers/UndoRedo.js
@@ -1,6 +1,6 @@
-import React from 'react'
-import { ActionCreators as UndoActionCreators } from 'redux-undo'
-import { connect } from 'react-redux'
+import React, { PropTypes } from 'react';
+import { ActionCreators as UndoActionCreators } from 'redux-undo';
+import { connect } from 'react-redux';
let UndoRedo = ({ canUndo, canRedo, onUndo, onRedo }) => (
@@ -11,25 +11,32 @@ let UndoRedo = ({ canUndo, canRedo, onUndo, onRedo }) => (
Redo
-)
+);
-const mapStateToProps = (state) => {
- return {
+UndoRedo.propTypes = {
+ canUndo: PropTypes.bool,
+ canRedo: PropTypes.bool,
+ onUndo: PropTypes.func,
+ onRedo: PropTypes.func,
+};
+
+const mapStateToProps = (state) => (
+ {
canUndo: state.todos.past.length > 0,
- canRedo: state.todos.future.length > 0
+ canRedo: state.todos.future.length > 0,
}
-}
+);
-const mapDispatchToProps = (dispatch) => {
- return {
+const mapDispatchToProps = (dispatch) => (
+ {
onUndo: () => dispatch(UndoActionCreators.undo()),
- onRedo: () => dispatch(UndoActionCreators.redo())
+ onRedo: () => dispatch(UndoActionCreators.redo()),
}
-}
+);
UndoRedo = connect(
mapStateToProps,
mapDispatchToProps
-)(UndoRedo)
+)(UndoRedo);
-export default UndoRedo
+export default UndoRedo;
diff --git a/examples/todos-with-undo/containers/VisibleTodoList.js b/examples/todos-with-undo/containers/VisibleTodoList.js
index 1d3ab4ee17..b97193b8c6 100644
--- a/examples/todos-with-undo/containers/VisibleTodoList.js
+++ b/examples/todos-with-undo/containers/VisibleTodoList.js
@@ -1,35 +1,35 @@
-import { connect } from 'react-redux'
-import { toggleTodo } from '../actions'
-import TodoList from '../components/TodoList'
+import { connect } from 'react-redux';
+import { toggleTodo } from '../actions';
+import TodoList from '../components/TodoList';
const getVisibleTodos = (todos, filter) => {
switch (filter) {
case 'SHOW_ALL':
- return todos
+ return todos;
case 'SHOW_COMPLETED':
- return todos.filter(t => t.completed)
+ return todos.filter(t => t.completed);
case 'SHOW_ACTIVE':
- return todos.filter(t => !t.completed)
+ return todos.filter(t => !t.completed);
}
-}
+};
-const mapStateToProps = (state) => {
- return {
- todos: getVisibleTodos(state.todos.present, state.visibilityFilter)
+const mapStateToProps = (state) => (
+ {
+ todos: getVisibleTodos(state.todos.present, state.visibilityFilter),
}
-}
+);
-const mapDispatchToProps = (dispatch) => {
- return {
+const mapDispatchToProps = (dispatch) => (
+ {
onTodoClick: (id) => {
- dispatch(toggleTodo(id))
- }
+ dispatch(toggleTodo(id));
+ },
}
-}
+);
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
-)(TodoList)
+)(TodoList);
-export default VisibleTodoList
+export default VisibleTodoList;
diff --git a/examples/todos-with-undo/index.js b/examples/todos-with-undo/index.js
index 300183e756..429f974f6f 100644
--- a/examples/todos-with-undo/index.js
+++ b/examples/todos-with-undo/index.js
@@ -1,17 +1,17 @@
-import 'babel-polyfill'
-import React from 'react'
-import { render } from 'react-dom'
-import { createStore } from 'redux'
-import { Provider } from 'react-redux'
-import App from './components/App'
-import todoApp from './reducers'
+import 'babel-polyfill';
+import React from 'react';
+import { render } from 'react-dom';
+import { createStore } from 'redux';
+import { Provider } from 'react-redux';
+import App from './components/App';
+import todoApp from './reducers';
-const store = createStore(todoApp)
+const store = createStore(todoApp);
-const rootElement = document.getElementById('root')
+const rootElement = document.getElementById('root');
render(
,
rootElement
-)
+);
diff --git a/examples/todos-with-undo/reducers/index.js b/examples/todos-with-undo/reducers/index.js
index 21f1662d67..10deb69edb 100644
--- a/examples/todos-with-undo/reducers/index.js
+++ b/examples/todos-with-undo/reducers/index.js
@@ -1,10 +1,10 @@
-import { combineReducers } from 'redux'
-import todos from './todos'
-import visibilityFilter from './visibilityFilter'
+import { combineReducers } from 'redux';
+import todos from './todos';
+import visibilityFilter from './visibilityFilter';
const todoApp = combineReducers({
todos,
- visibilityFilter
-})
+ visibilityFilter,
+});
-export default todoApp
+export default todoApp;
diff --git a/examples/todos-with-undo/reducers/todos.js b/examples/todos-with-undo/reducers/todos.js
index 1777081e96..912ab9e7e3 100644
--- a/examples/todos-with-undo/reducers/todos.js
+++ b/examples/todos-with-undo/reducers/todos.js
@@ -1,4 +1,4 @@
-import undoable, { distinctState } from 'redux-undo'
+import undoable, { distinctState } from 'redux-undo';
const todo = (state, action) => {
switch (action.type) {
@@ -6,39 +6,39 @@ const todo = (state, action) => {
return {
id: action.id,
text: action.text,
- completed: false
- }
+ completed: false,
+ };
case 'TOGGLE_TODO':
if (state.id !== action.id) {
- return state
+ return state;
}
return Object.assign({}, state, {
- completed: !state.completed
- })
+ completed: !state.completed,
+ });
default:
- return state
+ return state;
}
-}
+};
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
- todo(undefined, action)
- ]
+ todo(undefined, action),
+ ];
case 'TOGGLE_TODO':
return state.map(t =>
todo(t, action)
- )
+ );
default:
- return state
+ return state;
}
-}
+};
const undoableTodos = undoable(todos, {
- filter: distinctState()
-})
+ filter: distinctState(),
+});
-export default undoableTodos
+export default undoableTodos;
diff --git a/examples/todos-with-undo/reducers/visibilityFilter.js b/examples/todos-with-undo/reducers/visibilityFilter.js
index ed11971082..f0801e0369 100644
--- a/examples/todos-with-undo/reducers/visibilityFilter.js
+++ b/examples/todos-with-undo/reducers/visibilityFilter.js
@@ -1,10 +1,10 @@
const visibilityFilter = (state = 'SHOW_ALL', action) => {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
- return action.filter
+ return action.filter;
default:
- return state
+ return state;
}
-}
+};
-export default visibilityFilter
+export default visibilityFilter;
diff --git a/examples/todos/actions/index.js b/examples/todos/actions/index.js
index f64182ed3f..b68d41a81d 100644
--- a/examples/todos/actions/index.js
+++ b/examples/todos/actions/index.js
@@ -1,22 +1,22 @@
-let nextTodoId = 0
-export const addTodo = (text) => {
- return {
+let nextTodoId = 0;
+export const addTodo = (text) => (
+ {
type: 'ADD_TODO',
id: nextTodoId++,
- text
+ text,
}
-}
+);
-export const setVisibilityFilter = (filter) => {
- return {
+export const setVisibilityFilter = (filter) => (
+ {
type: 'SET_VISIBILITY_FILTER',
- filter
+ filter,
}
-}
+);
-export const toggleTodo = (id) => {
- return {
+export const toggleTodo = (id) => (
+ {
type: 'TOGGLE_TODO',
- id
+ id,
}
-}
+);
diff --git a/examples/todos/components/App.js b/examples/todos/components/App.js
index 62893936f4..844f3228d6 100644
--- a/examples/todos/components/App.js
+++ b/examples/todos/components/App.js
@@ -1,7 +1,7 @@
-import React from 'react'
-import Footer from './Footer'
-import AddTodo from '../containers/AddTodo'
-import VisibleTodoList from '../containers/VisibleTodoList'
+import React from 'react';
+import Footer from './Footer';
+import AddTodo from '../containers/AddTodo';
+import VisibleTodoList from '../containers/VisibleTodoList';
const App = () => (
@@ -9,6 +9,6 @@ const App = () => (
-)
+);
-export default App
+export default App;
diff --git a/examples/todos/components/Footer.js b/examples/todos/components/Footer.js
index 2d7527e745..839da1271f 100644
--- a/examples/todos/components/Footer.js
+++ b/examples/todos/components/Footer.js
@@ -1,5 +1,5 @@
-import React from 'react'
-import FilterLink from '../containers/FilterLink'
+import React from 'react';
+import FilterLink from '../containers/FilterLink';
const Footer = () => (
@@ -17,6 +17,6 @@ const Footer = () => (
Completed
-)
+);
-export default Footer
+export default Footer;
diff --git a/examples/todos/components/Link.js b/examples/todos/components/Link.js
index cb781442b7..71bcabda8a 100644
--- a/examples/todos/components/Link.js
+++ b/examples/todos/components/Link.js
@@ -1,26 +1,26 @@
-import React, { PropTypes } from 'react'
+import React, { PropTypes } from 'react';
const Link = ({ active, children, onClick }) => {
if (active) {
- return {children}
+ return {children} ;
}
return (
{
- e.preventDefault()
- onClick()
- }}
+ onClick={e => {
+ e.preventDefault();
+ onClick();
+ }}
>
{children}
- )
-}
+ );
+};
Link.propTypes = {
active: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
- onClick: PropTypes.func.isRequired
-}
+ onClick: PropTypes.func.isRequired,
+};
-export default Link
+export default Link;
diff --git a/examples/todos/components/Todo.js b/examples/todos/components/Todo.js
index 234ba77d11..3a6067187e 100644
--- a/examples/todos/components/Todo.js
+++ b/examples/todos/components/Todo.js
@@ -1,20 +1,20 @@
-import React, { PropTypes } from 'react'
+import React, { PropTypes } from 'react';
const Todo = ({ onClick, completed, text }) => (
{text}
-)
+);
Todo.propTypes = {
onClick: PropTypes.func.isRequired,
completed: PropTypes.bool.isRequired,
- text: PropTypes.string.isRequired
-}
+ text: PropTypes.string.isRequired,
+};
-export default Todo
+export default Todo;
diff --git a/examples/todos/components/TodoList.js b/examples/todos/components/TodoList.js
index bcd4b1ef59..dd55e7e8d7 100644
--- a/examples/todos/components/TodoList.js
+++ b/examples/todos/components/TodoList.js
@@ -1,5 +1,5 @@
-import React, { PropTypes } from 'react'
-import Todo from './Todo'
+import React, { PropTypes } from 'react';
+import Todo from './Todo';
const TodoList = ({ todos, onTodoClick }) => (
@@ -11,15 +11,15 @@ const TodoList = ({ todos, onTodoClick }) => (
/>
)}
-)
+);
TodoList.propTypes = {
todos: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
completed: PropTypes.bool.isRequired,
- text: PropTypes.string.isRequired
+ text: PropTypes.string.isRequired,
}).isRequired).isRequired,
- onTodoClick: PropTypes.func.isRequired
-}
+ onTodoClick: PropTypes.func.isRequired,
+};
-export default TodoList
+export default TodoList;
diff --git a/examples/todos/containers/AddTodo.js b/examples/todos/containers/AddTodo.js
index 39ad22fdb0..4b2f162acf 100644
--- a/examples/todos/containers/AddTodo.js
+++ b/examples/todos/containers/AddTodo.js
@@ -1,30 +1,39 @@
-import React from 'react'
-import { connect } from 'react-redux'
-import { addTodo } from '../actions'
+import React, { PropTypes } from 'react';
+import { connect } from 'react-redux';
+import { addTodo } from '../actions';
let AddTodo = ({ dispatch }) => {
- let input
+ let input;
return (
-
- )
-}
-AddTodo = connect()(AddTodo)
+ );
+};
-export default AddTodo
+AddTodo.propTypes = {
+ dispatch: PropTypes.func,
+};
+
+AddTodo = connect()(AddTodo);
+
+export default AddTodo;
diff --git a/examples/todos/containers/FilterLink.js b/examples/todos/containers/FilterLink.js
index 3ff3a93c8c..9e25875401 100644
--- a/examples/todos/containers/FilterLink.js
+++ b/examples/todos/containers/FilterLink.js
@@ -1,24 +1,22 @@
-import { connect } from 'react-redux'
-import { setVisibilityFilter } from '../actions'
-import Link from '../components/Link'
+import { connect } from 'react-redux';
+import { setVisibilityFilter } from '../actions';
+import Link from '../components/Link';
-const mapStateToProps = (state, ownProps) => {
- return {
- active: ownProps.filter === state.visibilityFilter
- }
-}
+const mapStateToProps = (state, ownProps) => (
+ { active: ownProps.filter === state.visibilityFilter }
+);
-const mapDispatchToProps = (dispatch, ownProps) => {
- return {
+const mapDispatchToProps = (dispatch, ownProps) => (
+ {
onClick: () => {
- dispatch(setVisibilityFilter(ownProps.filter))
- }
+ dispatch(setVisibilityFilter(ownProps.filter));
+ },
}
-}
+);
const FilterLink = connect(
mapStateToProps,
mapDispatchToProps
-)(Link)
+)(Link);
-export default FilterLink
+export default FilterLink;
diff --git a/examples/todos/containers/VisibleTodoList.js b/examples/todos/containers/VisibleTodoList.js
index dc301c99eb..a045f313cd 100644
--- a/examples/todos/containers/VisibleTodoList.js
+++ b/examples/todos/containers/VisibleTodoList.js
@@ -1,35 +1,33 @@
-import { connect } from 'react-redux'
-import { toggleTodo } from '../actions'
-import TodoList from '../components/TodoList'
+import { connect } from 'react-redux';
+import { toggleTodo } from '../actions';
+import TodoList from '../components/TodoList';
const getVisibleTodos = (todos, filter) => {
switch (filter) {
case 'SHOW_ALL':
- return todos
+ return todos;
case 'SHOW_COMPLETED':
- return todos.filter(t => t.completed)
+ return todos.filter(t => t.completed);
case 'SHOW_ACTIVE':
- return todos.filter(t => !t.completed)
+ return todos.filter(t => !t.completed);
}
-}
+};
-const mapStateToProps = (state) => {
- return {
- todos: getVisibleTodos(state.todos, state.visibilityFilter)
- }
-}
+const mapStateToProps = (state) => (
+ { todos: getVisibleTodos(state.todos, state.visibilityFilter) }
+);
-const mapDispatchToProps = (dispatch) => {
- return {
+const mapDispatchToProps = (dispatch) => (
+ {
onTodoClick: (id) => {
- dispatch(toggleTodo(id))
- }
+ dispatch(toggleTodo(id));
+ },
}
-}
+);
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
-)(TodoList)
+)(TodoList);
-export default VisibleTodoList
+export default VisibleTodoList;
diff --git a/examples/todos/index.js b/examples/todos/index.js
index 8904faa67f..0eb3d546df 100644
--- a/examples/todos/index.js
+++ b/examples/todos/index.js
@@ -1,16 +1,16 @@
-import 'babel-polyfill'
-import React from 'react'
-import { render } from 'react-dom'
-import { Provider } from 'react-redux'
-import { createStore } from 'redux'
-import todoApp from './reducers'
-import App from './components/App'
+import 'babel-polyfill';
+import React from 'react';
+import { render } from 'react-dom';
+import { Provider } from 'react-redux';
+import { createStore } from 'redux';
+import todoApp from './reducers';
+import App from './components/App';
-let store = createStore(todoApp)
+let store = createStore(todoApp);
render(
,
document.getElementById('root')
-)
+);
diff --git a/examples/todos/reducers/index.js b/examples/todos/reducers/index.js
index 21f1662d67..10deb69edb 100644
--- a/examples/todos/reducers/index.js
+++ b/examples/todos/reducers/index.js
@@ -1,10 +1,10 @@
-import { combineReducers } from 'redux'
-import todos from './todos'
-import visibilityFilter from './visibilityFilter'
+import { combineReducers } from 'redux';
+import todos from './todos';
+import visibilityFilter from './visibilityFilter';
const todoApp = combineReducers({
todos,
- visibilityFilter
-})
+ visibilityFilter,
+});
-export default todoApp
+export default todoApp;
diff --git a/examples/todos/reducers/todos.js b/examples/todos/reducers/todos.js
index c019cdcd8e..d0c26688f5 100644
--- a/examples/todos/reducers/todos.js
+++ b/examples/todos/reducers/todos.js
@@ -4,35 +4,35 @@ const todo = (state, action) => {
return {
id: action.id,
text: action.text,
- completed: false
- }
+ completed: false,
+ };
case 'TOGGLE_TODO':
if (state.id !== action.id) {
- return state
+ return state;
}
return Object.assign({}, state, {
- completed: !state.completed
- })
+ completed: !state.completed,
+ });
default:
- return state
+ return state;
}
-}
+};
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
- todo(undefined, action)
- ]
+ todo(undefined, action),
+ ];
case 'TOGGLE_TODO':
return state.map(t =>
todo(t, action)
- )
+ );
default:
- return state
+ return state;
}
-}
+};
-export default todos
+export default todos;
diff --git a/examples/todos/reducers/visibilityFilter.js b/examples/todos/reducers/visibilityFilter.js
index ed11971082..f0801e0369 100644
--- a/examples/todos/reducers/visibilityFilter.js
+++ b/examples/todos/reducers/visibilityFilter.js
@@ -1,10 +1,10 @@
const visibilityFilter = (state = 'SHOW_ALL', action) => {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
- return action.filter
+ return action.filter;
default:
- return state
+ return state;
}
-}
+};
-export default visibilityFilter
+export default visibilityFilter;
diff --git a/examples/todos/test/actions/todos.spec.js b/examples/todos/test/actions/todos.spec.js
index 0fe068c895..cd10f6f50d 100644
--- a/examples/todos/test/actions/todos.spec.js
+++ b/examples/todos/test/actions/todos.spec.js
@@ -1,26 +1,26 @@
-import expect from 'expect'
-import * as actions from '../../actions'
+import expect from 'expect';
+import * as actions from '../../actions';
describe('todo actions', () => {
it('addTodo should create ADD_TODO action', () => {
expect(actions.addTodo('Use Redux')).toEqual({
type: 'ADD_TODO',
id: 0,
- text: 'Use Redux'
- })
- })
+ text: 'Use Redux',
+ });
+ });
it('setVisibilityFilter should create SET_VISIBILITY_FILTER action', () => {
expect(actions.setVisibilityFilter('active')).toEqual({
type: 'SET_VISIBILITY_FILTER',
- filter: 'active'
- })
- })
+ filter: 'active',
+ });
+ });
it('toggleTodo should create TOGGLE_TODO action', () => {
expect(actions.toggleTodo(1)).toEqual({
type: 'TOGGLE_TODO',
- id: 1
- })
- })
-})
+ id: 1,
+ });
+ });
+});
diff --git a/examples/todos/test/reducers/todos.spec.js b/examples/todos/test/reducers/todos.spec.js
index 9fc41423a8..4cb6fcad0d 100644
--- a/examples/todos/test/reducers/todos.spec.js
+++ b/examples/todos/test/reducers/todos.spec.js
@@ -1,84 +1,84 @@
-import expect from 'expect'
-import todos from '../../reducers/todos'
+import expect from 'expect';
+import todos from '../../reducers/todos';
describe('todos reducer', () => {
it('should handle initial state', () => {
expect(
todos(undefined, {})
- ).toEqual([])
- })
+ ).toEqual([]);
+ });
it('should handle ADD_TODO', () => {
expect(
todos([], {
type: 'ADD_TODO',
text: 'Run the tests',
- id: 0
+ id: 0,
})
).toEqual([
{
text: 'Run the tests',
completed: false,
- id: 0
- }
- ])
+ id: 0,
+ },
+ ]);
expect(
todos([
{
text: 'Run the tests',
completed: false,
- id: 0
- }
+ id: 0,
+ },
], {
type: 'ADD_TODO',
text: 'Use Redux',
- id: 1
+ id: 1,
})
).toEqual([
{
text: 'Run the tests',
completed: false,
- id: 0
+ id: 0,
}, {
text: 'Use Redux',
completed: false,
- id: 1
- }
- ])
+ id: 1,
+ },
+ ]);
expect(
todos([
{
text: 'Run the tests',
completed: false,
- id: 0
+ id: 0,
}, {
text: 'Use Redux',
completed: false,
- id: 1
- }
+ id: 1,
+ },
], {
type: 'ADD_TODO',
text: 'Fix the tests',
- id: 2
+ id: 2,
})
).toEqual([
{
text: 'Run the tests',
completed: false,
- id: 0
+ id: 0,
}, {
text: 'Use Redux',
completed: false,
- id: 1
+ id: 1,
}, {
text: 'Fix the tests',
completed: false,
- id: 2
- }
- ])
- })
+ id: 2,
+ },
+ ]);
+ });
it('should handle TOGGLE_TODO', () => {
expect(
@@ -86,27 +86,26 @@ describe('todos reducer', () => {
{
text: 'Run the tests',
completed: false,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
+ id: 0,
+ },
], {
type: 'TOGGLE_TODO',
- id: 1
+ id: 1,
})
).toEqual([
{
text: 'Run the tests',
completed: true,
- id: 1
+ id: 1,
}, {
text: 'Use Redux',
completed: false,
- id: 0
- }
- ])
- })
-
-})
+ id: 0,
+ },
+ ]);
+ });
+});
diff --git a/examples/todos/test/setup.js b/examples/todos/test/setup.js
index c2e0f0cab2..b4e5ab07bf 100644
--- a/examples/todos/test/setup.js
+++ b/examples/todos/test/setup.js
@@ -1,5 +1,5 @@
-import { jsdom } from 'jsdom'
+import { jsdom } from 'jsdom';
-global.document = jsdom('')
-global.window = document.defaultView
-global.navigator = global.window.navigator
+global.document = jsdom('');
+global.window = document.defaultView;
+global.navigator = global.window.navigator;
diff --git a/examples/tree-view/actions/index.js b/examples/tree-view/actions/index.js
index 4183faf185..8d09f999b0 100644
--- a/examples/tree-view/actions/index.js
+++ b/examples/tree-view/actions/index.js
@@ -1,43 +1,43 @@
-export const INCREMENT = 'INCREMENT'
-export const CREATE_NODE = 'CREATE_NODE'
-export const DELETE_NODE = 'DELETE_NODE'
-export const ADD_CHILD = 'ADD_CHILD'
-export const REMOVE_CHILD = 'REMOVE_CHILD'
+export const INCREMENT = 'INCREMENT';
+export const CREATE_NODE = 'CREATE_NODE';
+export const DELETE_NODE = 'DELETE_NODE';
+export const ADD_CHILD = 'ADD_CHILD';
+export const REMOVE_CHILD = 'REMOVE_CHILD';
export function increment(nodeId) {
return {
type: INCREMENT,
- nodeId
- }
+ nodeId,
+ };
}
-let nextId = 0
+let nextId = 0;
export function createNode() {
return {
type: CREATE_NODE,
- nodeId: `new_${nextId++}`
- }
+ nodeId: `new_${nextId++}`,
+ };
}
export function deleteNode(nodeId) {
return {
type: DELETE_NODE,
- nodeId
- }
+ nodeId,
+ };
}
export function addChild(nodeId, childId) {
return {
type: ADD_CHILD,
nodeId,
- childId
- }
+ childId,
+ };
}
export function removeChild(nodeId, childId) {
return {
type: REMOVE_CHILD,
nodeId,
- childId
- }
+ childId,
+ };
}
diff --git a/examples/tree-view/containers/Node.js b/examples/tree-view/containers/Node.js
index 08e77ca188..4ff1b78763 100644
--- a/examples/tree-view/containers/Node.js
+++ b/examples/tree-view/containers/Node.js
@@ -1,49 +1,49 @@
-import React from 'react'
-import { Component } from 'react'
-import { connect } from 'react-redux'
-import * as actions from '../actions'
+import React, { PropTypes } from 'react';
+import { Component } from 'react';
+import { connect } from 'react-redux';
+import * as actions from '../actions';
export class Node extends Component {
constructor(props) {
- super(props)
- this.handleIncrementClick = this.handleIncrementClick.bind(this)
- this.handleRemoveClick = this.handleRemoveClick.bind(this)
- this.handleAddChildClick = this.handleAddChildClick.bind(this)
- this.renderChild = this.renderChild.bind(this)
+ super(props);
+ this.handleIncrementClick = this.handleIncrementClick.bind(this);
+ this.handleRemoveClick = this.handleRemoveClick.bind(this);
+ this.handleAddChildClick = this.handleAddChildClick.bind(this);
+ this.renderChild = this.renderChild.bind(this);
}
handleIncrementClick() {
- const { increment, id } = this.props
- increment(id)
+ const { increment, id } = this.props;
+ increment(id);
}
handleAddChildClick(e) {
- e.preventDefault()
+ e.preventDefault();
- const { addChild, createNode, id } = this.props
- const childId = createNode().nodeId
- addChild(id, childId)
+ const { addChild, createNode, id } = this.props;
+ const childId = createNode().nodeId;
+ addChild(id, childId);
}
handleRemoveClick(e) {
- e.preventDefault()
+ e.preventDefault();
- const { removeChild, deleteNode, parentId, id } = this.props
- removeChild(parentId, id)
- deleteNode(id)
+ const { removeChild, deleteNode, parentId, id } = this.props;
+ removeChild(parentId, id);
+ deleteNode(id);
}
renderChild(childId) {
- const { id } = this.props
+ const { id } = this.props;
return (
- )
+ );
}
render() {
- const { counter, parentId, childIds } = this.props
+ const { counter, parentId, childIds } = this.props;
return (
Counter: {counter}
@@ -53,8 +53,11 @@ export class Node extends Component {
{' '}
{typeof parentId !== 'undefined' ?
-
+
×
:
null
@@ -68,13 +71,25 @@ export class Node extends Component {
- )
+ );
}
}
+Node.propTypes = {
+ id: PropTypes.number,
+ counter: PropTypes.number,
+ increment: PropTypes.func,
+ addChild: PropTypes.func,
+ childIds: PropTypes.array,
+ createNode: PropTypes.func,
+ removeChild: PropTypes.func,
+ deleteNode: PropTypes.func,
+ parentId: PropTypes.number,
+};
+
function mapStateToProps(state, ownProps) {
- return state[ownProps.id]
+ return state[ownProps.id];
}
-const ConnectedNode = connect(mapStateToProps, actions)(Node)
-export default ConnectedNode
+const ConnectedNode = connect(mapStateToProps, actions)(Node);
+export default ConnectedNode;
diff --git a/examples/tree-view/generateTree.js b/examples/tree-view/generateTree.js
index 3f7fd1ea64..993f48719f 100644
--- a/examples/tree-view/generateTree.js
+++ b/examples/tree-view/generateTree.js
@@ -1,21 +1,21 @@
export default function generateTree() {
- let tree = {
+ const tree = {
0: {
id: 0,
counter: 0,
- childIds: []
- }
- }
+ childIds: [],
+ },
+ };
for (let i = 1; i < 1000; i++) {
- let parentId = Math.floor(Math.pow(Math.random(), 2) * i)
+ const parentId = Math.floor(Math.pow(Math.random(), 2) * i);
tree[i] = {
id: i,
counter: 0,
- childIds: []
- }
- tree[parentId].childIds.push(i)
+ childIds: [],
+ };
+ tree[parentId].childIds.push(i);
}
- return tree
+ return tree;
}
diff --git a/examples/tree-view/index.js b/examples/tree-view/index.js
index 31458aff8b..fae5996658 100644
--- a/examples/tree-view/index.js
+++ b/examples/tree-view/index.js
@@ -1,17 +1,17 @@
-import 'babel-polyfill'
-import React from 'react'
-import { render } from 'react-dom'
-import { Provider } from 'react-redux'
-import Node from './containers/Node'
-import configureStore from './store/configureStore'
-import generateTree from './generateTree'
+import 'babel-polyfill';
+import React from 'react';
+import { render } from 'react-dom';
+import { Provider } from 'react-redux';
+import Node from './containers/Node';
+import configureStore from './store/configureStore';
+import generateTree from './generateTree';
-const tree = generateTree()
-const store = configureStore(tree)
+const tree = generateTree();
+const store = configureStore(tree);
render(
,
document.getElementById('root')
-)
+);
diff --git a/examples/tree-view/reducers/index.js b/examples/tree-view/reducers/index.js
index 7e2493c3b6..2cc9d9716d 100644
--- a/examples/tree-view/reducers/index.js
+++ b/examples/tree-view/reducers/index.js
@@ -1,13 +1,13 @@
-import { INCREMENT, ADD_CHILD, REMOVE_CHILD, CREATE_NODE, DELETE_NODE } from '../actions'
+import { INCREMENT, ADD_CHILD, REMOVE_CHILD, CREATE_NODE, DELETE_NODE } from '../actions';
function childIds(state, action) {
switch (action.type) {
case ADD_CHILD:
- return [ ...state, action.childId ]
+ return [...state, action.childId];
case REMOVE_CHILD:
- return state.filter(id => id !== action.childId)
+ return state.filter(id => id !== action.childId);
default:
- return state
+ return state;
}
}
@@ -17,46 +17,46 @@ function node(state, action) {
return {
id: action.nodeId,
counter: 0,
- childIds: []
- }
+ childIds: [],
+ };
case INCREMENT:
return Object.assign({}, state, {
- counter: state.counter + 1
- })
+ counter: state.counter + 1,
+ });
case ADD_CHILD:
case REMOVE_CHILD:
return Object.assign({}, state, {
- childIds: childIds(state.childIds, action)
- })
+ childIds: childIds(state.childIds, action),
+ });
default:
- return state
+ return state;
}
}
function getAllDescendantIds(state, nodeId) {
return state[nodeId].childIds.reduce((acc, childId) => (
- [ ...acc, childId, ...getAllDescendantIds(state, childId) ]
- ), [])
+ [...acc, childId, ...getAllDescendantIds(state, childId)]
+ ), []);
}
function deleteMany(state, ids) {
- state = Object.assign({}, state)
- ids.forEach(id => delete state[id])
- return state
+ const newState = Object.assign({}, state);
+ ids.forEach(id => delete newState[id]);
+ return state;
}
export default function (state = {}, action) {
- const { nodeId } = action
+ const { nodeId } = action;
if (typeof nodeId === 'undefined') {
- return state
+ return state;
}
if (action.type === DELETE_NODE) {
- const descendantIds = getAllDescendantIds(state, nodeId)
- return deleteMany(state, [ nodeId, ...descendantIds ])
+ const descendantIds = getAllDescendantIds(state, nodeId);
+ return deleteMany(state, [nodeId, ...descendantIds]);
}
return Object.assign({}, state, {
- [nodeId]: node(state[nodeId], action)
- })
+ [nodeId]: node(state[nodeId], action),
+ });
}
diff --git a/examples/tree-view/store/configureStore.js b/examples/tree-view/store/configureStore.js
index 33390d1fbe..a6fbf9c5ae 100644
--- a/examples/tree-view/store/configureStore.js
+++ b/examples/tree-view/store/configureStore.js
@@ -1,16 +1,16 @@
-import { createStore } from 'redux'
-import reducer from '../reducers'
+import { createStore } from 'redux';
+import reducer from '../reducers';
export default function configureStore(initialState) {
- const store = createStore(reducer, initialState)
+ const store = createStore(reducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
- const nextReducer = require('../reducers').default
- store.replaceReducer(nextReducer)
- })
+ const nextReducer = require('../reducers').default;
+ store.replaceReducer(nextReducer);
+ });
}
- return store
+ return store;
}
diff --git a/examples/tree-view/test/node.spec.js b/examples/tree-view/test/node.spec.js
index 7f01cb5977..776d16e246 100644
--- a/examples/tree-view/test/node.spec.js
+++ b/examples/tree-view/test/node.spec.js
@@ -1,7 +1,7 @@
-import expect from 'expect'
-import React from 'react'
-import { shallow } from 'enzyme'
-import ConnectedNode, { Node } from '../containers/Node'
+import expect from 'expect';
+import React from 'react';
+import { shallow } from 'enzyme';
+import ConnectedNode, { Node } from '../containers/Node';
function setup(id, counter, childIds, parentId) {
const actions = {
@@ -9,83 +9,83 @@ function setup(id, counter, childIds, parentId) {
removeChild: expect.createSpy(),
deleteNode: expect.createSpy(),
createNode: expect.createSpy(),
- addChild: expect.createSpy()
- }
+ addChild: expect.createSpy(),
+ };
const eventArgs = {
- preventDefault: expect.createSpy()
- }
+ preventDefault: expect.createSpy(),
+ };
const component = shallow(
- )
+ );
return {
- component: component,
+ component,
removeLink: component.findWhere(n => n.type() === 'a' && n.contains('×')),
addLink: component.findWhere(n => n.type() === 'a' && n.contains('Add child')),
button: component.find('button'),
childNodes: component.find(ConnectedNode),
- actions: actions,
- eventArgs: eventArgs
- }
+ actions,
+ eventArgs,
+ };
}
describe('Node component', () => {
it('should display counter', () => {
- const { component } = setup(1, 23, [])
- expect(component.text()).toMatch(/^Counter: 23/)
- })
+ const { component } = setup(1, 23, []);
+ expect(component.text()).toMatch(/^Counter: 23/);
+ });
it('should call increment on button click', () => {
- const { button, actions } = setup(1, 23, [])
- button.simulate('click')
+ const { button, actions } = setup(1, 23, []);
+ button.simulate('click');
- expect(actions.increment).toHaveBeenCalledWith(1)
- })
+ expect(actions.increment).toHaveBeenCalledWith(1);
+ });
it('should not render remove link', () => {
- const { removeLink } = setup(1, 23, [])
- expect(removeLink.length).toEqual(0)
- })
+ const { removeLink } = setup(1, 23, []);
+ expect(removeLink.length).toEqual(0);
+ });
it('should call createNode action on Add child click', () => {
- const { addLink, actions, eventArgs } = setup(2, 1, [])
- actions.createNode.andReturn({ nodeId: 3 })
- addLink.simulate('click', eventArgs)
+ const { addLink, actions, eventArgs } = setup(2, 1, []);
+ actions.createNode.andReturn({ nodeId: 3 });
+ addLink.simulate('click', eventArgs);
- expect(actions.createNode).toHaveBeenCalled()
- })
+ expect(actions.createNode).toHaveBeenCalled();
+ });
it('should call addChild action on Add child click', () => {
- const { addLink, actions, eventArgs } = setup(2, 1, [])
- actions.createNode.andReturn({ nodeId: 3 })
+ const { addLink, actions, eventArgs } = setup(2, 1, []);
+ actions.createNode.andReturn({ nodeId: 3 });
- addLink.simulate('click', eventArgs)
+ addLink.simulate('click', eventArgs);
- expect(actions.addChild).toHaveBeenCalledWith(2, 3)
- })
+ expect(actions.addChild).toHaveBeenCalledWith(2, 3);
+ });
describe('when given childIds', () => {
it('should render child nodes', () => {
- const { childNodes } = setup(1, 23, [ 2, 3 ])
- expect(childNodes.length).toEqual(2)
- })
- })
+ const { childNodes } = setup(1, 23, [2, 3]);
+ expect(childNodes.length).toEqual(2);
+ });
+ });
describe('when given parentId', () => {
it('should call removeChild action on remove link click', () => {
- const { removeLink, actions, eventArgs } = setup(2, 1, [], 1)
- removeLink.simulate('click', eventArgs)
+ const { removeLink, actions, eventArgs } = setup(2, 1, [], 1);
+ removeLink.simulate('click', eventArgs);
- expect(actions.removeChild).toHaveBeenCalledWith(1, 2)
- })
+ expect(actions.removeChild).toHaveBeenCalledWith(1, 2);
+ });
it('should call deleteNode action on remove link click', () => {
- const { removeLink, actions, eventArgs } = setup(2, 1, [], 1)
- removeLink.simulate('click', eventArgs)
+ const { removeLink, actions, eventArgs } = setup(2, 1, [], 1);
+ removeLink.simulate('click', eventArgs);
- expect(actions.deleteNode).toHaveBeenCalledWith(2)
- })
- })
-})
+ expect(actions.deleteNode).toHaveBeenCalledWith(2);
+ });
+ });
+});
diff --git a/examples/tree-view/test/reducer.spec.js b/examples/tree-view/test/reducer.spec.js
index 1dd222e86d..9616d5b9a2 100644
--- a/examples/tree-view/test/reducer.spec.js
+++ b/examples/tree-view/test/reducer.spec.js
@@ -1,164 +1,164 @@
-import expect from 'expect'
-import deepFreeze from 'deep-freeze'
-import reducer from '../reducers'
-import { increment, createNode, deleteNode, addChild, removeChild } from '../actions'
+import expect from 'expect';
+import deepFreeze from 'deep-freeze';
+import reducer from '../reducers';
+import { increment, createNode, deleteNode, addChild, removeChild } from '../actions';
describe('reducer', () => {
it('should provide the initial state', () => {
- expect(reducer(undefined, {})).toEqual({})
- })
+ expect(reducer(undefined, {})).toEqual({});
+ });
it('should handle INCREMENT action', () => {
const stateBefore = {
- 'node_0': {
+ node_0: {
id: 'node_0',
counter: 0,
- childIds: []
- }
- }
- const action = increment('node_0')
+ childIds: [],
+ },
+ };
+ const action = increment('node_0');
const stateAfter = {
- 'node_0': {
+ node_0: {
id: 'node_0',
counter: 1,
- childIds: []
- }
- }
+ childIds: [],
+ },
+ };
- deepFreeze(stateBefore)
- deepFreeze(action)
+ deepFreeze(stateBefore);
+ deepFreeze(action);
- expect(reducer(stateBefore, action)).toEqual(stateAfter)
- })
+ expect(reducer(stateBefore, action)).toEqual(stateAfter);
+ });
it('should handle CREATE_NODE action', () => {
- const stateBefore = {}
- const action = createNode()
+ const stateBefore = {};
+ const action = createNode();
const stateAfter = {
[action.nodeId]: {
id: action.nodeId,
counter: 0,
- childIds: []
- }
- }
+ childIds: [],
+ },
+ };
- deepFreeze(stateBefore)
- deepFreeze(action)
+ deepFreeze(stateBefore);
+ deepFreeze(action);
- expect(reducer(stateBefore, action)).toEqual(stateAfter)
- })
+ expect(reducer(stateBefore, action)).toEqual(stateAfter);
+ });
it('should handle DELETE_NODE action', () => {
const stateBefore = {
- 'node_0': {
+ node_0: {
id: 'node_0',
counter: 0,
- childIds: [ 'node_1' ]
+ childIds: ['node_1'],
},
- 'node_1': {
+ node_1: {
id: 'node_1',
counter: 0,
- childIds: []
+ childIds: [],
},
- 'node_2': {
+ node_2: {
id: 'node_2',
counter: 0,
- childIds: [ 'node_3', 'node_4' ]
+ childIds: ['node_3', 'node_4'],
},
- 'node_3': {
+ node_3: {
id: 'node_3',
counter: 0,
- childIds: []
+ childIds: [],
},
- 'node_4': {
+ node_4: {
id: 'node_4',
counter: 0,
- childIds: []
- }
- }
- const action = deleteNode('node_2')
+ childIds: [],
+ },
+ };
+ const action = deleteNode('node_2');
const stateAfter = {
- 'node_0': {
+ node_0: {
id: 'node_0',
counter: 0,
- childIds: [ 'node_1' ]
+ childIds: ['node_1'],
},
- 'node_1': {
+ node_1: {
id: 'node_1',
counter: 0,
- childIds: []
- }
- }
+ childIds: [],
+ },
+ };
- deepFreeze(stateBefore)
- deepFreeze(action)
+ deepFreeze(stateBefore);
+ deepFreeze(action);
- expect(reducer(stateBefore, action)).toEqual(stateAfter)
- })
+ expect(reducer(stateBefore, action)).toEqual(stateAfter);
+ });
it('should handle ADD_CHILD action', () => {
const stateBefore = {
- 'node_0': {
+ node_0: {
id: 'node_0',
counter: 0,
- childIds: []
+ childIds: [],
},
- 'node_1': {
+ node_1: {
id: 'node_1',
counter: 0,
- childIds: []
- }
- }
- const action = addChild('node_0', 'node_1')
+ childIds: [],
+ },
+ };
+ const action = addChild('node_0', 'node_1');
const stateAfter = {
- 'node_0': {
+ node_0: {
id: 'node_0',
counter: 0,
- childIds: [ 'node_1' ]
+ childIds: ['node_1'],
},
- 'node_1': {
+ node_1: {
id: 'node_1',
counter: 0,
- childIds: []
- }
- }
+ childIds: [],
+ },
+ };
- deepFreeze(stateBefore)
- deepFreeze(action)
+ deepFreeze(stateBefore);
+ deepFreeze(action);
- expect(reducer(stateBefore, action)).toEqual(stateAfter)
- })
+ expect(reducer(stateBefore, action)).toEqual(stateAfter);
+ });
it('should handle REMOVE_CHILD action', () => {
const stateBefore = {
- 'node_0': {
+ node_0: {
id: 'node_0',
counter: 0,
- childIds: [ 'node_1' ]
+ childIds: ['node_1'],
},
- 'node_1': {
+ node_1: {
id: 'node_1',
counter: 0,
- childIds: []
- }
- }
- const action = removeChild('node_0', 'node_1')
+ childIds: [],
+ },
+ };
+ const action = removeChild('node_0', 'node_1');
const stateAfter = {
- 'node_0': {
+ node_0: {
id: 'node_0',
counter: 0,
- childIds: []
+ childIds: [],
},
- 'node_1': {
+ node_1: {
id: 'node_1',
counter: 0,
- childIds: []
- }
- }
+ childIds: [],
+ },
+ };
- deepFreeze(stateBefore)
- deepFreeze(action)
+ deepFreeze(stateBefore);
+ deepFreeze(action);
- expect(reducer(stateBefore, action)).toEqual(stateAfter)
- })
-})
+ expect(reducer(stateBefore, action)).toEqual(stateAfter);
+ });
+});
diff --git a/examples/universal/client/index.js b/examples/universal/client/index.js
index 16d2b5cd53..6d8b26c701 100644
--- a/examples/universal/client/index.js
+++ b/examples/universal/client/index.js
@@ -1,17 +1,17 @@
-import 'babel-polyfill'
-import React from 'react'
-import { render } from 'react-dom'
-import { Provider } from 'react-redux'
-import configureStore from '../common/store/configureStore'
-import App from '../common/containers/App'
+import 'babel-polyfill';
+import React from 'react';
+import { render } from 'react-dom';
+import { Provider } from 'react-redux';
+import configureStore from '../common/store/configureStore';
+import App from '../common/containers/App';
-const initialState = window.__INITIAL_STATE__
-const store = configureStore(initialState)
-const rootElement = document.getElementById('app')
+const initialState = window.__INITIAL_STATE__;
+const store = configureStore(initialState);
+const rootElement = document.getElementById('app');
render(
-
+
,
rootElement
-)
+);
diff --git a/examples/universal/common/actions/index.js b/examples/universal/common/actions/index.js
index cdd84fe881..9f19cbd342 100644
--- a/examples/universal/common/actions/index.js
+++ b/examples/universal/common/actions/index.js
@@ -1,42 +1,42 @@
-export const SET_COUNTER = 'SET_COUNTER'
-export const INCREMENT_COUNTER = 'INCREMENT_COUNTER'
-export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'
+export const SET_COUNTER = 'SET_COUNTER';
+export const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
+export const DECREMENT_COUNTER = 'DECREMENT_COUNTER';
export function set(value) {
return {
type: SET_COUNTER,
- payload: value
- }
+ payload: value,
+ };
}
export function increment() {
return {
- type: INCREMENT_COUNTER
- }
+ type: INCREMENT_COUNTER,
+ };
}
export function decrement() {
return {
- type: DECREMENT_COUNTER
- }
+ type: DECREMENT_COUNTER,
+ };
}
export function incrementIfOdd() {
return (dispatch, getState) => {
- const { counter } = getState()
+ const { counter } = getState();
if (counter % 2 === 0) {
- return
+ return;
}
- dispatch(increment())
- }
+ dispatch(increment());
+ };
}
export function incrementAsync(delay = 1000) {
return dispatch => {
setTimeout(() => {
- dispatch(increment())
- }, delay)
- }
+ dispatch(increment());
+ }, delay);
+ };
}
diff --git a/examples/universal/common/api/counter.js b/examples/universal/common/api/counter.js
index 2bdd1f3b64..81caa6c6ec 100644
--- a/examples/universal/common/api/counter.js
+++ b/examples/universal/common/api/counter.js
@@ -1,12 +1,13 @@
function getRandomInt(min, max) {
- return Math.floor(Math.random() * (max - min)) + min
+ return Math.floor(Math.random() * (max - min)) + min;
}
export function fetchCounter(callback) {
- // Rather than immediately returning, we delay our code with a timeout to simulate asynchronous behavior
+ // Rather than immediately returning, we delay our code with a timeout
+ // to simulate asynchronous behavior
setTimeout(() => {
- callback(getRandomInt(1, 100))
- }, 500)
+ callback(getRandomInt(1, 100));
+ }, 500);
// In the case of a real world API call, you'll normally run into a Promise like this:
// API.getUser().then(user => callback(user))
diff --git a/examples/universal/common/components/Counter.js b/examples/universal/common/components/Counter.js
index 61532854e4..0823e71f95 100644
--- a/examples/universal/common/components/Counter.js
+++ b/examples/universal/common/components/Counter.js
@@ -1,8 +1,8 @@
-import React, { Component, PropTypes } from 'react'
+import React, { Component, PropTypes } from 'react';
class Counter extends Component {
render() {
- const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props
+ const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props;
return (
Clicked: {counter} times
@@ -15,7 +15,7 @@ class Counter extends Component {
{' '}
incrementAsync()}>Increment async
- )
+ );
}
}
@@ -24,7 +24,7 @@ Counter.propTypes = {
incrementIfOdd: PropTypes.func.isRequired,
incrementAsync: PropTypes.func.isRequired,
decrement: PropTypes.func.isRequired,
- counter: PropTypes.number.isRequired
-}
+ counter: PropTypes.number.isRequired,
+};
-export default Counter
+export default Counter;
diff --git a/examples/universal/common/containers/App.js b/examples/universal/common/containers/App.js
index 3a931cece5..e11389d745 100644
--- a/examples/universal/common/containers/App.js
+++ b/examples/universal/common/containers/App.js
@@ -1,16 +1,16 @@
-import { bindActionCreators } from 'redux'
-import { connect } from 'react-redux'
-import Counter from '../components/Counter'
-import * as CounterActions from '../actions'
+import { bindActionCreators } from 'redux';
+import { connect } from 'react-redux';
+import Counter from '../components/Counter';
+import * as CounterActions from '../actions';
function mapStateToProps(state) {
return {
- counter: state.counter
- }
+ counter: state.counter,
+ };
}
function mapDispatchToProps(dispatch) {
- return bindActionCreators(CounterActions, dispatch)
+ return bindActionCreators(CounterActions, dispatch);
}
-export default connect(mapStateToProps, mapDispatchToProps)(Counter)
+export default connect(mapStateToProps, mapDispatchToProps)(Counter);
diff --git a/examples/universal/common/reducers/counter.js b/examples/universal/common/reducers/counter.js
index ba4458db85..0da96153b7 100644
--- a/examples/universal/common/reducers/counter.js
+++ b/examples/universal/common/reducers/counter.js
@@ -1,14 +1,14 @@
-import { SET_COUNTER, INCREMENT_COUNTER, DECREMENT_COUNTER } from '../actions'
+import { SET_COUNTER, INCREMENT_COUNTER, DECREMENT_COUNTER } from '../actions';
export default function counter(state = 0, action) {
switch (action.type) {
case SET_COUNTER:
- return action.payload
+ return action.payload;
case INCREMENT_COUNTER:
- return state + 1
+ return state + 1;
case DECREMENT_COUNTER:
- return state - 1
+ return state - 1;
default:
- return state
+ return state;
}
}
diff --git a/examples/universal/common/reducers/index.js b/examples/universal/common/reducers/index.js
index b200fb3252..eba07a1561 100644
--- a/examples/universal/common/reducers/index.js
+++ b/examples/universal/common/reducers/index.js
@@ -1,8 +1,8 @@
-import { combineReducers } from 'redux'
-import counter from './counter'
+import { combineReducers } from 'redux';
+import counter from './counter';
const rootReducer = combineReducers({
- counter
-})
+ counter,
+});
-export default rootReducer
+export default rootReducer;
diff --git a/examples/universal/common/store/configureStore.js b/examples/universal/common/store/configureStore.js
index 5ce5e52e71..43aa32862e 100644
--- a/examples/universal/common/store/configureStore.js
+++ b/examples/universal/common/store/configureStore.js
@@ -1,21 +1,21 @@
-import { createStore, applyMiddleware } from 'redux'
-import thunk from 'redux-thunk'
-import rootReducer from '../reducers'
+import { createStore, applyMiddleware } from 'redux';
+import thunk from 'redux-thunk';
+import rootReducer from '../reducers';
export default function configureStore(initialState) {
const store = createStore(
rootReducer,
initialState,
applyMiddleware(thunk)
- )
+ );
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
- const nextRootReducer = require('../reducers').default
- store.replaceReducer(nextRootReducer)
- })
+ const nextRootReducer = require('../reducers').default;
+ store.replaceReducer(nextRootReducer);
+ });
}
- return store
+ return store;
}
diff --git a/examples/universal/index.js b/examples/universal/index.js
index b2cf35e14c..0b513ce749 100644
--- a/examples/universal/index.js
+++ b/examples/universal/index.js
@@ -1 +1 @@
-require('./client')
+require('./client');
diff --git a/examples/universal/server/index.js b/examples/universal/server/index.js
index 04171d26bf..ad6d3cd513 100644
--- a/examples/universal/server/index.js
+++ b/examples/universal/server/index.js
@@ -1,2 +1,2 @@
-require('babel-register')
-require('./server')
+require('babel-register');
+require('./server');
diff --git a/package.json b/package.json
index b4bacafaac..3df9b34ecc 100644
--- a/package.json
+++ b/package.json
@@ -68,7 +68,6 @@
"devDependencies": {
"babel-cli": "^6.3.15",
"babel-core": "^6.3.15",
- "babel-eslint": "^4.1.6",
"babel-loader": "^6.2.0",
"babel-plugin-check-es2015-constants": "^6.3.13",
"babel-plugin-transform-es2015-arrow-functions": "^6.3.13",
@@ -92,9 +91,9 @@
"babel-register": "^6.3.13",
"cross-env": "^1.0.7",
"es3ify": "^0.2.0",
- "eslint": "^1.10.3",
- "eslint-config-rackt": "^1.1.1",
- "eslint-plugin-react": "^3.16.1",
+ "eslint": "^2.5.3",
+ "eslint-config-airbnb": "^6.2.0",
+ "eslint-plugin-react": "^4.2.3",
"expect": "^1.8.0",
"gitbook-cli": "^0.3.4",
"glob": "^6.0.4",
diff --git a/src/applyMiddleware.js b/src/applyMiddleware.js
index 52c95fc8a7..22f42fa0db 100644
--- a/src/applyMiddleware.js
+++ b/src/applyMiddleware.js
@@ -1,4 +1,4 @@
-import compose from './compose'
+import compose from './compose';
/**
* Creates a store enhancer that applies middleware to the dispatch method
@@ -18,20 +18,20 @@ import compose from './compose'
*/
export default function applyMiddleware(...middlewares) {
return (createStore) => (reducer, initialState, enhancer) => {
- var store = createStore(reducer, initialState, enhancer)
- var dispatch = store.dispatch
- var chain = []
+ const store = createStore(reducer, initialState, enhancer);
+ let dispatch = store.dispatch;
+ let chain = [];
- var middlewareAPI = {
+ const middlewareAPI = {
getState: store.getState,
- dispatch: (action) => dispatch(action)
- }
- chain = middlewares.map(middleware => middleware(middlewareAPI))
- dispatch = compose(...chain)(store.dispatch)
+ dispatch: (action) => dispatch(action),
+ };
+ chain = middlewares.map(middleware => middleware(middlewareAPI));
+ dispatch = compose(...chain)(store.dispatch);
return {
...store,
- dispatch
- }
- }
+ dispatch,
+ };
+ };
}
diff --git a/src/bindActionCreators.js b/src/bindActionCreators.js
index e70e270fd4..3b4f4c5abf 100644
--- a/src/bindActionCreators.js
+++ b/src/bindActionCreators.js
@@ -1,5 +1,5 @@
function bindActionCreator(actionCreator, dispatch) {
- return (...args) => dispatch(actionCreator(...args))
+ return (...args) => dispatch(actionCreator(...args));
}
/**
@@ -25,24 +25,24 @@ function bindActionCreator(actionCreator, dispatch) {
*/
export default function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') {
- return bindActionCreator(actionCreators, dispatch)
+ return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error(
`bindActionCreators expected an object or a function, instead received ${actionCreators === null ? 'null' : typeof actionCreators}. ` +
- `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
- )
+ 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
+ );
}
- var keys = Object.keys(actionCreators)
- var boundActionCreators = {}
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i]
- var actionCreator = actionCreators[key]
+ const keys = Object.keys(actionCreators);
+ const boundActionCreators = {};
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i];
+ const actionCreator = actionCreators[key];
if (typeof actionCreator === 'function') {
- boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
+ boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
}
}
- return boundActionCreators
+ return boundActionCreators;
}
diff --git a/src/combineReducers.js b/src/combineReducers.js
index 5a8a20a9b7..20863a2e46 100644
--- a/src/combineReducers.js
+++ b/src/combineReducers.js
@@ -1,77 +1,77 @@
-import { ActionTypes } from './createStore'
-import isPlainObject from 'lodash/isPlainObject'
-import warning from './utils/warning'
+import { ActionTypes } from './createStore';
+import isPlainObject from 'lodash/isPlainObject';
+import warning from './utils/warning';
function getUndefinedStateErrorMessage(key, action) {
- var actionType = action && action.type
- var actionName = actionType && `"${actionType.toString()}"` || 'an action'
+ const actionType = action && action.type;
+ const actionName = actionType && `"${actionType.toString()}"` || 'an action';
return (
`Given action ${actionName}, reducer "${key}" returned undefined. ` +
- `To ignore an action, you must explicitly return the previous state.`
- )
+ 'To ignore an action, you must explicitly return the previous state.'
+ );
}
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) {
- var reducerKeys = Object.keys(reducers)
- var argumentName = action && action.type === ActionTypes.INIT ?
+ const reducerKeys = Object.keys(reducers);
+ const argumentName = action && action.type === ActionTypes.INIT ?
'initialState argument passed to createStore' :
- 'previous state received by the reducer'
+ 'previous state received by the reducer';
if (reducerKeys.length === 0) {
return (
'Store does not have a valid reducer. Make sure the argument passed ' +
'to combineReducers is an object whose values are reducers.'
- )
+ );
}
if (!isPlainObject(inputState)) {
return (
`The ${argumentName} has unexpected type of "` +
({}).toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] +
- `". Expected argument to be an object with the following ` +
+ '". Expected argument to be an object with the following ' +
`keys: "${reducerKeys.join('", "')}"`
- )
+ );
}
- var unexpectedKeys = Object.keys(inputState).filter(key => !reducers.hasOwnProperty(key))
+ const unexpectedKeys = Object.keys(inputState).filter(key => !reducers.hasOwnProperty(key));
if (unexpectedKeys.length > 0) {
return (
`Unexpected ${unexpectedKeys.length > 1 ? 'keys' : 'key'} ` +
`"${unexpectedKeys.join('", "')}" found in ${argumentName}. ` +
- `Expected to find one of the known reducer keys instead: ` +
+ 'Expected to find one of the known reducer keys instead: ' +
`"${reducerKeys.join('", "')}". Unexpected keys will be ignored.`
- )
+ );
}
}
function assertReducerSanity(reducers) {
Object.keys(reducers).forEach(key => {
- var reducer = reducers[key]
- var initialState = reducer(undefined, { type: ActionTypes.INIT })
+ const reducer = reducers[key];
+ const initialState = reducer(undefined, { type: ActionTypes.INIT });
if (typeof initialState === 'undefined') {
throw new Error(
`Reducer "${key}" returned undefined during initialization. ` +
- `If the state passed to the reducer is undefined, you must ` +
- `explicitly return the initial state. The initial state may ` +
- `not be undefined.`
- )
+ 'If the state passed to the reducer is undefined, you must ' +
+ 'explicitly return the initial state. The initial state may ' +
+ 'not be undefined.'
+ );
}
- var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.')
+ const type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
if (typeof reducer(undefined, { type }) === 'undefined') {
throw new Error(
`Reducer "${key}" returned undefined when probed with a random type. ` +
`Don't try to handle ${ActionTypes.INIT} or other actions in "redux/*" ` +
- `namespace. They are considered private. Instead, you must return the ` +
- `current state for any unknown actions, unless it is undefined, ` +
- `in which case you must return the initial state, regardless of the ` +
- `action type. The initial state may not be undefined.`
- )
+ 'namespace. They are considered private. Instead, you must return the ' +
+ 'current state for any unknown actions, unless it is undefined, ' +
+ 'in which case you must return the initial state, regardless of the ' +
+ 'action type. The initial state may not be undefined.'
+ );
}
- })
+ });
}
/**
@@ -91,49 +91,49 @@ function assertReducerSanity(reducers) {
* passed object, and builds a state object with the same shape.
*/
export default function combineReducers(reducers) {
- var reducerKeys = Object.keys(reducers)
- var finalReducers = {}
- for (var i = 0; i < reducerKeys.length; i++) {
- var key = reducerKeys[i]
+ const reducerKeys = Object.keys(reducers);
+ const finalReducers = {};
+ for (let i = 0; i < reducerKeys.length; i++) {
+ const key = reducerKeys[i];
if (typeof reducers[key] === 'function') {
- finalReducers[key] = reducers[key]
+ finalReducers[key] = reducers[key];
}
}
- var finalReducerKeys = Object.keys(finalReducers)
+ const finalReducerKeys = Object.keys(finalReducers);
- var sanityError
+ let sanityError;
try {
- assertReducerSanity(finalReducers)
+ assertReducerSanity(finalReducers);
} catch (e) {
- sanityError = e
+ sanityError = e;
}
return function combination(state = {}, action) {
if (sanityError) {
- throw sanityError
+ throw sanityError;
}
if (process.env.NODE_ENV !== 'production') {
- var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action)
+ const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action);
if (warningMessage) {
- warning(warningMessage)
+ warning(warningMessage);
}
}
- var hasChanged = false
- var nextState = {}
- for (var i = 0; i < finalReducerKeys.length; i++) {
- var key = finalReducerKeys[i]
- var reducer = finalReducers[key]
- var previousStateForKey = state[key]
- var nextStateForKey = reducer(previousStateForKey, action)
+ let hasChanged = false;
+ const nextState = {};
+ for (let i = 0; i < finalReducerKeys.length; i++) {
+ const key = finalReducerKeys[i];
+ const reducer = finalReducers[key];
+ const previousStateForKey = state[key];
+ const nextStateForKey = reducer(previousStateForKey, action);
if (typeof nextStateForKey === 'undefined') {
- var errorMessage = getUndefinedStateErrorMessage(key, action)
- throw new Error(errorMessage)
+ const errorMessage = getUndefinedStateErrorMessage(key, action);
+ throw new Error(errorMessage);
}
- nextState[key] = nextStateForKey
- hasChanged = hasChanged || nextStateForKey !== previousStateForKey
+ nextState[key] = nextStateForKey;
+ hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
- return hasChanged ? nextState : state
- }
+ return hasChanged ? nextState : state;
+ };
}
diff --git a/src/compose.js b/src/compose.js
index 72ba4dd42b..658fa92079 100644
--- a/src/compose.js
+++ b/src/compose.js
@@ -8,16 +8,16 @@
* from right to left. For example, compose(f, g, h) is identical to doing
* (...args) => f(g(h(...args))).
*/
-
+
export default function compose(...funcs) {
return (...args) => {
if (funcs.length === 0) {
- return args[0]
+ return args[0];
}
- const last = funcs[funcs.length - 1]
- const rest = funcs.slice(0, -1)
+ const last = funcs[funcs.length - 1];
+ const rest = funcs.slice(0, -1);
- return rest.reduceRight((composed, f) => f(composed), last(...args))
- }
+ return rest.reduceRight((composed, f) => f(composed), last(...args));
+ };
}
diff --git a/src/createStore.js b/src/createStore.js
index 68097d1ce3..643ee50354 100644
--- a/src/createStore.js
+++ b/src/createStore.js
@@ -1,4 +1,4 @@
-import isPlainObject from 'lodash/isPlainObject'
+import isPlainObject from 'lodash/isPlainObject';
/**
* These are private action types reserved by Redux.
@@ -6,9 +6,9 @@ import isPlainObject from 'lodash/isPlainObject'
* If the current state is undefined, you must return the initial state.
* Do not reference these action types directly in your code.
*/
-export var ActionTypes = {
- INIT: '@@redux/INIT'
-}
+export const ActionTypes = {
+ INIT: '@@redux/INIT',
+};
/**
* Creates a Redux store that holds the state tree.
@@ -37,31 +37,31 @@ export var ActionTypes = {
*/
export default function createStore(reducer, initialState, enhancer) {
if (typeof initialState === 'function' && typeof enhancer === 'undefined') {
- enhancer = initialState
- initialState = undefined
+ enhancer = initialState;
+ initialState = undefined;
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
- throw new Error('Expected the enhancer to be a function.')
+ throw new Error('Expected the enhancer to be a function.');
}
- return enhancer(createStore)(reducer, initialState)
+ return enhancer(createStore)(reducer, initialState);
}
if (typeof reducer !== 'function') {
- throw new Error('Expected the reducer to be a function.')
+ throw new Error('Expected the reducer to be a function.');
}
- var currentReducer = reducer
- var currentState = initialState
- var currentListeners = []
- var nextListeners = currentListeners
- var isDispatching = false
+ let currentReducer = reducer;
+ let currentState = initialState;
+ let currentListeners = [];
+ let nextListeners = currentListeners;
+ let isDispatching = false;
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
- nextListeners = currentListeners.slice()
+ nextListeners = currentListeners.slice();
}
}
@@ -71,7 +71,7 @@ export default function createStore(reducer, initialState, enhancer) {
* @returns {any} The current state tree of your application.
*/
function getState() {
- return currentState
+ return currentState;
}
/**
@@ -99,25 +99,25 @@ export default function createStore(reducer, initialState, enhancer) {
*/
function subscribe(listener) {
if (typeof listener !== 'function') {
- throw new Error('Expected listener to be a function.')
+ throw new Error('Expected listener to be a function.');
}
- var isSubscribed = true
+ let isSubscribed = true;
- ensureCanMutateNextListeners()
- nextListeners.push(listener)
+ ensureCanMutateNextListeners();
+ nextListeners.push(listener);
return function unsubscribe() {
if (!isSubscribed) {
- return
+ return;
}
- isSubscribed = false
+ isSubscribed = false;
- ensureCanMutateNextListeners()
- var index = nextListeners.indexOf(listener)
- nextListeners.splice(index, 1)
- }
+ ensureCanMutateNextListeners();
+ const index = nextListeners.indexOf(listener);
+ nextListeners.splice(index, 1);
+ };
}
/**
@@ -150,33 +150,33 @@ export default function createStore(reducer, initialState, enhancer) {
throw new Error(
'Actions must be plain objects. ' +
'Use custom middleware for async actions.'
- )
+ );
}
if (typeof action.type === 'undefined') {
throw new Error(
'Actions may not have an undefined "type" property. ' +
'Have you misspelled a constant?'
- )
+ );
}
if (isDispatching) {
- throw new Error('Reducers may not dispatch actions.')
+ throw new Error('Reducers may not dispatch actions.');
}
try {
- isDispatching = true
- currentState = currentReducer(currentState, action)
+ isDispatching = true;
+ currentState = currentReducer(currentState, action);
} finally {
- isDispatching = false
+ isDispatching = false;
}
- var listeners = currentListeners = nextListeners
- for (var i = 0; i < listeners.length; i++) {
- listeners[i]()
+ const listeners = currentListeners = nextListeners;
+ for (let i = 0; i < listeners.length; i++) {
+ listeners[i]();
}
- return action
+ return action;
}
/**
@@ -191,22 +191,22 @@ export default function createStore(reducer, initialState, enhancer) {
*/
function replaceReducer(nextReducer) {
if (typeof nextReducer !== 'function') {
- throw new Error('Expected the nextReducer to be a function.')
+ throw new Error('Expected the nextReducer to be a function.');
}
- currentReducer = nextReducer
- dispatch({ type: ActionTypes.INIT })
+ currentReducer = nextReducer;
+ dispatch({ type: ActionTypes.INIT });
}
// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
- dispatch({ type: ActionTypes.INIT })
+ dispatch({ type: ActionTypes.INIT });
return {
dispatch,
subscribe,
getState,
- replaceReducer
- }
+ replaceReducer,
+ };
}
diff --git a/src/index.js b/src/index.js
index 5d0d8cd624..3507de853c 100644
--- a/src/index.js
+++ b/src/index.js
@@ -1,9 +1,9 @@
-import createStore from './createStore'
-import combineReducers from './combineReducers'
-import bindActionCreators from './bindActionCreators'
-import applyMiddleware from './applyMiddleware'
-import compose from './compose'
-import warning from './utils/warning'
+import createStore from './createStore';
+import combineReducers from './combineReducers';
+import bindActionCreators from './bindActionCreators';
+import applyMiddleware from './applyMiddleware';
+import compose from './compose';
+import warning from './utils/warning';
/*
* This is a dummy function to check if the function name has been altered by minification.
@@ -22,7 +22,7 @@ if (
'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' +
'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' +
'to ensure you have the correct code for your production build.'
- )
+ );
}
export {
@@ -30,5 +30,5 @@ export {
combineReducers,
bindActionCreators,
applyMiddleware,
- compose
-}
+ compose,
+};
diff --git a/src/utils/warning.js b/src/utils/warning.js
index 6eca67f06d..fd3803a584 100644
--- a/src/utils/warning.js
+++ b/src/utils/warning.js
@@ -7,13 +7,13 @@
export default function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
- console.error(message)
+ console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
- throw new Error(message)
+ throw new Error(message);
/* eslint-disable no-empty */
} catch (e) { }
/* eslint-enable no-empty */
diff --git a/test/applyMiddleware.spec.js b/test/applyMiddleware.spec.js
index 988981a1ce..6d247b519c 100644
--- a/test/applyMiddleware.spec.js
+++ b/test/applyMiddleware.spec.js
@@ -1,97 +1,97 @@
-import expect from 'expect'
-import { createStore, applyMiddleware } from '../src/index'
-import * as reducers from './helpers/reducers'
-import { addTodo, addTodoAsync, addTodoIfEmpty } from './helpers/actionCreators'
-import { thunk } from './helpers/middleware'
+import expect from 'expect';
+import { createStore, applyMiddleware } from '../src/index';
+import * as reducers from './helpers/reducers';
+import { addTodo, addTodoAsync, addTodoIfEmpty } from './helpers/actionCreators';
+import { thunk } from './helpers/middleware';
describe('applyMiddleware', () => {
it('wraps dispatch method with middleware once', () => {
function test(spyOnMethods) {
return methods => {
- spyOnMethods(methods)
- return next => action => next(action)
- }
+ spyOnMethods(methods);
+ return next => action => next(action);
+ };
}
- const spy = expect.createSpy(() => {})
- const store = applyMiddleware(test(spy), thunk)(createStore)(reducers.todos)
+ const spy = expect.createSpy(() => {});
+ const store = applyMiddleware(test(spy), thunk)(createStore)(reducers.todos);
- store.dispatch(addTodo('Use Redux'))
- store.dispatch(addTodo('Flux FTW!'))
+ store.dispatch(addTodo('Use Redux'));
+ store.dispatch(addTodo('Flux FTW!'));
- expect(spy.calls.length).toEqual(1)
+ expect(spy.calls.length).toEqual(1);
expect(Object.keys(spy.calls[0].arguments[0])).toEqual([
'getState',
- 'dispatch'
- ])
+ 'dispatch',
+ ]);
- expect(store.getState()).toEqual([ { id: 1, text: 'Use Redux' }, { id: 2, text: 'Flux FTW!' } ])
- })
+ expect(store.getState()).toEqual([{ id: 1, text: 'Use Redux' }, { id: 2, text: 'Flux FTW!' }]);
+ });
it('passes recursive dispatches through the middleware chain', () => {
function test(spyOnMethods) {
return () => next => action => {
- spyOnMethods(action)
- return next(action)
- }
+ spyOnMethods(action);
+ return next(action);
+ };
}
- const spy = expect.createSpy(() => {})
- const store = applyMiddleware(test(spy), thunk)(createStore)(reducers.todos)
+ const spy = expect.createSpy(() => {});
+ const store = applyMiddleware(test(spy), thunk)(createStore)(reducers.todos);
return store.dispatch(addTodoAsync('Use Redux')).then(() => {
- expect(spy.calls.length).toEqual(2)
- })
- })
+ expect(spy.calls.length).toEqual(2);
+ });
+ });
it('works with thunk middleware', done => {
- const store = applyMiddleware(thunk)(createStore)(reducers.todos)
+ const store = applyMiddleware(thunk)(createStore)(reducers.todos);
- store.dispatch(addTodoIfEmpty('Hello'))
+ store.dispatch(addTodoIfEmpty('Hello'));
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
- }
- ])
+ text: 'Hello',
+ },
+ ]);
- store.dispatch(addTodoIfEmpty('Hello'))
+ store.dispatch(addTodoIfEmpty('Hello'));
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
- }
- ])
+ text: 'Hello',
+ },
+ ]);
- store.dispatch(addTodo('World'))
+ store.dispatch(addTodo('World'));
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
+ text: 'Hello',
},
{
id: 2,
- text: 'World'
- }
- ])
+ text: 'World',
+ },
+ ]);
store.dispatch(addTodoAsync('Maybe')).then(() => {
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
+ text: 'Hello',
},
{
id: 2,
- text: 'World'
+ text: 'World',
},
{
id: 3,
- text: 'Maybe'
- }
- ])
- done()
- })
- })
-})
+ text: 'Maybe',
+ },
+ ]);
+ done();
+ });
+ });
+});
diff --git a/test/bindActionCreators.spec.js b/test/bindActionCreators.spec.js
index f9fcc5c264..fee3a02506 100644
--- a/test/bindActionCreators.spec.js
+++ b/test/bindActionCreators.spec.js
@@ -1,38 +1,38 @@
-import expect from 'expect'
-import { bindActionCreators, createStore } from '../src'
-import { todos } from './helpers/reducers'
-import * as actionCreators from './helpers/actionCreators'
+import expect from 'expect';
+import { bindActionCreators, createStore } from '../src';
+import { todos } from './helpers/reducers';
+import * as actionCreators from './helpers/actionCreators';
describe('bindActionCreators', () => {
- let store
- let actionCreatorFunctions
+ let store;
+ let actionCreatorFunctions;
beforeEach(() => {
- store = createStore(todos)
- actionCreatorFunctions = { ...actionCreators }
+ store = createStore(todos);
+ actionCreatorFunctions = { ...actionCreators };
Object.keys(actionCreatorFunctions).forEach(key => {
if (typeof actionCreatorFunctions[key] !== 'function') {
- delete actionCreatorFunctions[key]
+ delete actionCreatorFunctions[key];
}
- })
- })
+ });
+ });
it('wraps the action creators with the dispatch function', () => {
- const boundActionCreators = bindActionCreators(actionCreators, store.dispatch)
+ const boundActionCreators = bindActionCreators(actionCreators, store.dispatch);
expect(
Object.keys(boundActionCreators)
).toEqual(
Object.keys(actionCreatorFunctions)
- )
+ );
- const action = boundActionCreators.addTodo('Hello')
+ const action = boundActionCreators.addTodo('Hello');
expect(action).toEqual(
actionCreators.addTodo('Hello')
- )
+ );
expect(store.getState()).toEqual([
- { id: 1, text: 'Hello' }
- ])
- })
+ { id: 1, text: 'Hello' },
+ ]);
+ });
it('skips non-function values in the passed object', () => {
const boundActionCreators = bindActionCreators({
@@ -41,50 +41,50 @@ describe('bindActionCreators', () => {
bar: 'baz',
wow: undefined,
much: {},
- test: null
- }, store.dispatch)
+ test: null,
+ }, store.dispatch);
expect(
Object.keys(boundActionCreators)
).toEqual(
Object.keys(actionCreatorFunctions)
- )
- })
+ );
+ });
it('supports wrapping a single function only', () => {
- const actionCreator = actionCreators.addTodo
- const boundActionCreator = bindActionCreators(actionCreator, store.dispatch)
+ const actionCreator = actionCreators.addTodo;
+ const boundActionCreator = bindActionCreators(actionCreator, store.dispatch);
- const action = boundActionCreator('Hello')
- expect(action).toEqual(actionCreator('Hello'))
+ const action = boundActionCreator('Hello');
+ expect(action).toEqual(actionCreator('Hello'));
expect(store.getState()).toEqual([
- { id: 1, text: 'Hello' }
- ])
- })
+ { id: 1, text: 'Hello' },
+ ]);
+ });
it('throws for an undefined actionCreator', () => {
expect(() => {
- bindActionCreators(undefined, store.dispatch)
+ bindActionCreators(undefined, store.dispatch);
}).toThrow(
'bindActionCreators expected an object or a function, instead received undefined. ' +
'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
- )
- })
+ );
+ });
it('throws for a null actionCreator', () => {
expect(() => {
- bindActionCreators(null, store.dispatch)
+ bindActionCreators(null, store.dispatch);
}).toThrow(
'bindActionCreators expected an object or a function, instead received null. ' +
'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
- )
- })
+ );
+ });
it('throws for a primitive actionCreator', () => {
expect(() => {
- bindActionCreators('string', store.dispatch)
+ bindActionCreators('string', store.dispatch);
}).toThrow(
'bindActionCreators expected an object or a function, instead received string. ' +
'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
- )
- })
-})
+ );
+ });
+});
diff --git a/test/combineReducers.spec.js b/test/combineReducers.spec.js
index d861ba371f..da81083a91 100644
--- a/test/combineReducers.spec.js
+++ b/test/combineReducers.spec.js
@@ -1,241 +1,239 @@
-import expect from 'expect'
-import { combineReducers } from '../src'
-import createStore, { ActionTypes } from '../src/createStore'
+import expect from 'expect';
+import { combineReducers } from '../src';
+import createStore, { ActionTypes } from '../src/createStore';
describe('Utils', () => {
describe('combineReducers', () => {
it('returns a composite reducer that maps the state keys to given reducers', () => {
const reducer = combineReducers({
- counter: (state = 0, action) =>
- action.type === 'increment' ? state + 1 : state,
- stack: (state = [], action) =>
- action.type === 'push' ? [ ...state, action.value ] : state
- })
-
- const s1 = reducer({}, { type: 'increment' })
- expect(s1).toEqual({ counter: 1, stack: [] })
- const s2 = reducer(s1, { type: 'push', value: 'a' })
- expect(s2).toEqual({ counter: 1, stack: [ 'a' ] })
- })
+ counter: (state = 0, action) => (action.type === 'increment' ? state + 1 : state),
+ stack: (state = [], action) => (action.type === 'push' ? [...state, action.value] : state),
+ });
+
+ const s1 = reducer({}, { type: 'increment' });
+ expect(s1).toEqual({ counter: 1, stack: [] });
+ const s2 = reducer(s1, { type: 'push', value: 'a' });
+ expect(s2).toEqual({ counter: 1, stack: ['a'] });
+ });
it('ignores all props which are not a function', () => {
const reducer = combineReducers({
fake: true,
broken: 'string',
another: { nested: 'object' },
- stack: (state = []) => state
- })
+ stack: (state = []) => state,
+ });
expect(
Object.keys(reducer({ }, { type: 'push' }))
- ).toEqual([ 'stack' ])
- })
+ ).toEqual(['stack']);
+ });
it('throws an error if a reducer returns undefined handling an action', () => {
const reducer = combineReducers({
counter(state = 0, action) {
switch (action && action.type) {
case 'increment':
- return state + 1
+ return state + 1;
case 'decrement':
- return state - 1
+ return state - 1;
case 'whatever':
case null:
case undefined:
- return undefined
+ return undefined;
default:
- return state
+ return state;
}
- }
- })
+ },
+ });
expect(
() => reducer({ counter: 0 }, { type: 'whatever' })
).toThrow(
/"whatever".*"counter"/
- )
+ );
expect(
() => reducer({ counter: 0 }, null)
).toThrow(
/"counter".*an action/
- )
+ );
expect(
() => reducer({ counter: 0 }, { })
).toThrow(
/"counter".*an action/
- )
- })
+ );
+ });
it('throws an error on first call if a reducer returns undefined initializing', () => {
const reducer = combineReducers({
counter(state, action) {
switch (action.type) {
case 'increment':
- return state + 1
+ return state + 1;
case 'decrement':
- return state - 1
+ return state - 1;
default:
- return state
+ return state;
}
- }
- })
+ },
+ });
expect(() => reducer({ })).toThrow(
/"counter".*initialization/
- )
- })
+ );
+ });
it('catches error thrown in reducer when initializing and re-throw', () => {
const reducer = combineReducers({
throwingReducer() {
- throw new Error('Error thrown in reducer')
- }
- })
+ throw new Error('Error thrown in reducer');
+ },
+ });
expect(() => reducer({ })).toThrow(
/Error thrown in reducer/
- )
- })
+ );
+ });
it('allows a symbol to be used as an action type', () => {
- const increment = Symbol('INCREMENT')
+ const increment = Symbol('INCREMENT');
const reducer = combineReducers({
counter(state = 0, action) {
switch (action.type) {
case increment:
- return state + 1
+ return state + 1;
default:
- return state
+ return state;
}
- }
- })
+ },
+ });
- expect(reducer({ counter: 0 }, { type: increment }).counter).toEqual(1)
- })
+ expect(reducer({ counter: 0 }, { type: increment }).counter).toEqual(1);
+ });
it('maintains referential equality if the reducers it is combining do', () => {
const reducer = combineReducers({
child1(state = { }) {
- return state
+ return state;
},
child2(state = { }) {
- return state
+ return state;
},
child3(state = { }) {
- return state
- }
- })
+ return state;
+ },
+ });
- const initialState = reducer(undefined, '@@INIT')
- expect(reducer(initialState, { type: 'FOO' })).toBe(initialState)
- })
+ const initialState = reducer(undefined, '@@INIT');
+ expect(reducer(initialState, { type: 'FOO' })).toBe(initialState);
+ });
it('does not have referential equality if one of the reducers changes something', () => {
const reducer = combineReducers({
child1(state = { }) {
- return state
+ return state;
},
child2(state = { count: 0 }, action) {
switch (action.type) {
case 'increment':
- return { count: state.count + 1 }
+ return { count: state.count + 1 };
default:
- return state
+ return state;
}
},
child3(state = { }) {
- return state
- }
- })
+ return state;
+ },
+ });
- const initialState = reducer(undefined, '@@INIT')
- expect(reducer(initialState, { type: 'increment' })).toNotBe(initialState)
- })
+ const initialState = reducer(undefined, '@@INIT');
+ expect(reducer(initialState, { type: 'increment' })).toNotBe(initialState);
+ });
it('throws an error on first call if a reducer attempts to handle a private action', () => {
const reducer = combineReducers({
counter(state, action) {
switch (action.type) {
case 'increment':
- return state + 1
+ return state + 1;
case 'decrement':
- return state - 1
+ return state - 1;
// Never do this in your code:
case ActionTypes.INIT:
- return 0
+ return 0;
default:
- return undefined
+ return undefined;
}
- }
- })
+ },
+ });
expect(() => reducer()).toThrow(
/"counter".*private/
- )
- })
+ );
+ });
it('warns if no reducers are passed to combineReducers', () => {
- const spy = expect.spyOn(console, 'error')
- const reducer = combineReducers({ })
- reducer({ })
+ const spy = expect.spyOn(console, 'error');
+ const reducer = combineReducers({ });
+ reducer({ });
expect(spy.calls[0].arguments[0]).toMatch(
/Store does not have a valid reducer/
- )
- spy.restore()
- })
+ );
+ spy.restore();
+ });
it('warns if input state does not match reducer shape', () => {
- const spy = expect.spyOn(console, 'error')
+ const spy = expect.spyOn(console, 'error');
const reducer = combineReducers({
foo(state = { bar: 1 }) {
- return state
+ return state;
},
baz(state = { qux: 3 }) {
- return state
- }
- })
+ return state;
+ },
+ });
- reducer()
- expect(spy.calls.length).toBe(0)
+ reducer();
+ expect(spy.calls.length).toBe(0);
- reducer({ foo: { bar: 2 } })
- expect(spy.calls.length).toBe(0)
+ reducer({ foo: { bar: 2 } });
+ expect(spy.calls.length).toBe(0);
reducer({
foo: { bar: 2 },
- baz: { qux: 4 }
- })
- expect(spy.calls.length).toBe(0)
+ baz: { qux: 4 },
+ });
+ expect(spy.calls.length).toBe(0);
- createStore(reducer, { bar: 2 })
+ createStore(reducer, { bar: 2 });
expect(spy.calls[0].arguments[0]).toMatch(
/Unexpected key "bar".*createStore.*instead: "foo", "baz"/
- )
+ );
- createStore(reducer, { bar: 2, qux: 4 })
+ createStore(reducer, { bar: 2, qux: 4 });
expect(spy.calls[1].arguments[0]).toMatch(
/Unexpected keys "bar", "qux".*createStore.*instead: "foo", "baz"/
- )
+ );
- createStore(reducer, 1)
+ createStore(reducer, 1);
expect(spy.calls[2].arguments[0]).toMatch(
/createStore has unexpected type of "Number".*keys: "foo", "baz"/
- )
+ );
- reducer({ bar: 2 })
+ reducer({ bar: 2 });
expect(spy.calls[3].arguments[0]).toMatch(
/Unexpected key "bar".*reducer.*instead: "foo", "baz"/
- )
+ );
- reducer({ bar: 2, qux: 4 })
+ reducer({ bar: 2, qux: 4 });
expect(spy.calls[4].arguments[0]).toMatch(
/Unexpected keys "bar", "qux".*reducer.*instead: "foo", "baz"/
- )
+ );
- reducer(1)
+ reducer(1);
expect(spy.calls[5].arguments[0]).toMatch(
/reducer has unexpected type of "Number".*keys: "foo", "baz"/
- )
+ );
- spy.restore()
- })
- })
-})
+ spy.restore();
+ });
+ });
+});
diff --git a/test/compose.spec.js b/test/compose.spec.js
index a55efe5008..11fea6575c 100644
--- a/test/compose.spec.js
+++ b/test/compose.spec.js
@@ -1,37 +1,37 @@
-import expect from 'expect'
-import { compose } from '../src'
+import expect from 'expect';
+import { compose } from '../src';
describe('Utils', () => {
describe('compose', () => {
it('composes from right to left', () => {
- const double = x => x * 2
- const square = x => x * x
- expect(compose(square)(5)).toBe(25)
- expect(compose(square, double)(5)).toBe(100)
- expect(compose(double, square, double)(5)).toBe(200)
- })
+ const double = x => x * 2;
+ const square = x => x * x;
+ expect(compose(square)(5)).toBe(25);
+ expect(compose(square, double)(5)).toBe(100);
+ expect(compose(double, square, double)(5)).toBe(200);
+ });
it('composes functions from right to left', () => {
- const a = next => x => next(x + 'a')
- const b = next => x => next(x + 'b')
- const c = next => x => next(x + 'c')
- const final = x => x
+ const a = next => x => next(`${x}a`);
+ const b = next => x => next(`${x}b`);
+ const c = next => x => next(`${x}c`);
+ const final = x => x;
- expect(compose(a, b, c)(final)('')).toBe('abc')
- expect(compose(b, c, a)(final)('')).toBe('bca')
- expect(compose(c, a, b)(final)('')).toBe('cab')
- })
+ expect(compose(a, b, c)(final)('')).toBe('abc');
+ expect(compose(b, c, a)(final)('')).toBe('bca');
+ expect(compose(c, a, b)(final)('')).toBe('cab');
+ });
it('can be seeded with multiple arguments', () => {
- const square = x => x * x
- const add = (x, y) => x + y
- expect(compose(square, add)(1, 2)).toBe(9)
- })
+ const square = x => x * x;
+ const add = (x, y) => x + y;
+ expect(compose(square, add)(1, 2)).toBe(9);
+ });
it('returns the first given argument if given no functions', () => {
- expect(compose()(1, 2)).toBe(1)
- expect(compose()(3)).toBe(3)
- expect(compose()()).toBe(undefined)
- })
- })
-})
+ expect(compose()(1, 2)).toBe(1);
+ expect(compose()(3)).toBe(3);
+ expect(compose()()).toBe(undefined);
+ });
+ });
+});
diff --git a/test/createStore.spec.js b/test/createStore.spec.js
index 3a8af0630b..ea36f0d6da 100644
--- a/test/createStore.spec.js
+++ b/test/createStore.spec.js
@@ -1,613 +1,613 @@
-import expect from 'expect'
-import { createStore, combineReducers } from '../src/index'
-import { addTodo, dispatchInMiddle, throwError, unknownAction } from './helpers/actionCreators'
-import * as reducers from './helpers/reducers'
+import expect from 'expect';
+import { createStore, combineReducers } from '../src/index';
+import { addTodo, dispatchInMiddle, throwError, unknownAction } from './helpers/actionCreators';
+import * as reducers from './helpers/reducers';
describe('createStore', () => {
it('exposes the public API', () => {
- const store = createStore(combineReducers(reducers))
- const methods = Object.keys(store)
+ const store = createStore(combineReducers(reducers));
+ const methods = Object.keys(store);
- expect(methods.length).toBe(4)
- expect(methods).toContain('subscribe')
- expect(methods).toContain('dispatch')
- expect(methods).toContain('getState')
- expect(methods).toContain('replaceReducer')
- })
+ expect(methods.length).toBe(4);
+ expect(methods).toContain('subscribe');
+ expect(methods).toContain('dispatch');
+ expect(methods).toContain('getState');
+ expect(methods).toContain('replaceReducer');
+ });
it('throws if reducer is not a function', () => {
expect(() =>
createStore()
- ).toThrow()
+ ).toThrow();
expect(() =>
createStore('test')
- ).toThrow()
+ ).toThrow();
expect(() =>
createStore({})
- ).toThrow()
+ ).toThrow();
expect(() =>
createStore(() => {})
- ).toNotThrow()
- })
+ ).toNotThrow();
+ });
it('passes the initial action and the initial state', () => {
const store = createStore(reducers.todos, [
{
id: 1,
- text: 'Hello'
- }
- ])
+ text: 'Hello',
+ },
+ ]);
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
- }
- ])
- })
+ text: 'Hello',
+ },
+ ]);
+ });
it('applies the reducer to the previous state', () => {
- const store = createStore(reducers.todos)
- expect(store.getState()).toEqual([])
+ const store = createStore(reducers.todos);
+ expect(store.getState()).toEqual([]);
- store.dispatch(unknownAction())
- expect(store.getState()).toEqual([])
+ store.dispatch(unknownAction());
+ expect(store.getState()).toEqual([]);
- store.dispatch(addTodo('Hello'))
+ store.dispatch(addTodo('Hello'));
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
- }
- ])
+ text: 'Hello',
+ },
+ ]);
- store.dispatch(addTodo('World'))
+ store.dispatch(addTodo('World'));
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
+ text: 'Hello',
}, {
id: 2,
- text: 'World'
- }
- ])
- })
+ text: 'World',
+ },
+ ]);
+ });
it('applies the reducer to the initial state', () => {
const store = createStore(reducers.todos, [
{
id: 1,
- text: 'Hello'
- }
- ])
+ text: 'Hello',
+ },
+ ]);
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
- }
- ])
+ text: 'Hello',
+ },
+ ]);
- store.dispatch(unknownAction())
+ store.dispatch(unknownAction());
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
- }
- ])
+ text: 'Hello',
+ },
+ ]);
- store.dispatch(addTodo('World'))
+ store.dispatch(addTodo('World'));
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
+ text: 'Hello',
}, {
id: 2,
- text: 'World'
- }
- ])
- })
+ text: 'World',
+ },
+ ]);
+ });
it('preserves the state when replacing a reducer', () => {
- const store = createStore(reducers.todos)
- store.dispatch(addTodo('Hello'))
- store.dispatch(addTodo('World'))
+ const store = createStore(reducers.todos);
+ store.dispatch(addTodo('Hello'));
+ store.dispatch(addTodo('World'));
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
+ text: 'Hello',
},
{
id: 2,
- text: 'World'
- }
- ])
+ text: 'World',
+ },
+ ]);
- store.replaceReducer(reducers.todosReverse)
+ store.replaceReducer(reducers.todosReverse);
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
+ text: 'Hello',
}, {
id: 2,
- text: 'World'
- }
- ])
+ text: 'World',
+ },
+ ]);
- store.dispatch(addTodo('Perhaps'))
+ store.dispatch(addTodo('Perhaps'));
expect(store.getState()).toEqual([
{
id: 3,
- text: 'Perhaps'
+ text: 'Perhaps',
},
{
id: 1,
- text: 'Hello'
+ text: 'Hello',
},
{
id: 2,
- text: 'World'
- }
- ])
+ text: 'World',
+ },
+ ]);
- store.replaceReducer(reducers.todos)
+ store.replaceReducer(reducers.todos);
expect(store.getState()).toEqual([
{
id: 3,
- text: 'Perhaps'
+ text: 'Perhaps',
},
{
id: 1,
- text: 'Hello'
+ text: 'Hello',
},
{
id: 2,
- text: 'World'
- }
- ])
+ text: 'World',
+ },
+ ]);
- store.dispatch(addTodo('Surely'))
+ store.dispatch(addTodo('Surely'));
expect(store.getState()).toEqual([
{
id: 3,
- text: 'Perhaps'
+ text: 'Perhaps',
},
{
id: 1,
- text: 'Hello'
+ text: 'Hello',
},
{
id: 2,
- text: 'World'
+ text: 'World',
},
{
id: 4,
- text: 'Surely'
- }
- ])
- })
+ text: 'Surely',
+ },
+ ]);
+ });
it('supports multiple subscriptions', () => {
- const store = createStore(reducers.todos)
- const listenerA = expect.createSpy(() => {})
- const listenerB = expect.createSpy(() => {})
+ const store = createStore(reducers.todos);
+ const listenerA = expect.createSpy(() => {});
+ const listenerB = expect.createSpy(() => {});
- let unsubscribeA = store.subscribe(listenerA)
- store.dispatch(unknownAction())
- expect(listenerA.calls.length).toBe(1)
- expect(listenerB.calls.length).toBe(0)
+ let unsubscribeA = store.subscribe(listenerA);
+ store.dispatch(unknownAction());
+ expect(listenerA.calls.length).toBe(1);
+ expect(listenerB.calls.length).toBe(0);
- store.dispatch(unknownAction())
- expect(listenerA.calls.length).toBe(2)
- expect(listenerB.calls.length).toBe(0)
+ store.dispatch(unknownAction());
+ expect(listenerA.calls.length).toBe(2);
+ expect(listenerB.calls.length).toBe(0);
- const unsubscribeB = store.subscribe(listenerB)
- expect(listenerA.calls.length).toBe(2)
- expect(listenerB.calls.length).toBe(0)
+ const unsubscribeB = store.subscribe(listenerB);
+ expect(listenerA.calls.length).toBe(2);
+ expect(listenerB.calls.length).toBe(0);
- store.dispatch(unknownAction())
- expect(listenerA.calls.length).toBe(3)
- expect(listenerB.calls.length).toBe(1)
+ store.dispatch(unknownAction());
+ expect(listenerA.calls.length).toBe(3);
+ expect(listenerB.calls.length).toBe(1);
- unsubscribeA()
- expect(listenerA.calls.length).toBe(3)
- expect(listenerB.calls.length).toBe(1)
+ unsubscribeA();
+ expect(listenerA.calls.length).toBe(3);
+ expect(listenerB.calls.length).toBe(1);
- store.dispatch(unknownAction())
- expect(listenerA.calls.length).toBe(3)
- expect(listenerB.calls.length).toBe(2)
+ store.dispatch(unknownAction());
+ expect(listenerA.calls.length).toBe(3);
+ expect(listenerB.calls.length).toBe(2);
- unsubscribeB()
- expect(listenerA.calls.length).toBe(3)
- expect(listenerB.calls.length).toBe(2)
+ unsubscribeB();
+ expect(listenerA.calls.length).toBe(3);
+ expect(listenerB.calls.length).toBe(2);
- store.dispatch(unknownAction())
- expect(listenerA.calls.length).toBe(3)
- expect(listenerB.calls.length).toBe(2)
+ store.dispatch(unknownAction());
+ expect(listenerA.calls.length).toBe(3);
+ expect(listenerB.calls.length).toBe(2);
- unsubscribeA = store.subscribe(listenerA)
- expect(listenerA.calls.length).toBe(3)
- expect(listenerB.calls.length).toBe(2)
+ unsubscribeA = store.subscribe(listenerA);
+ expect(listenerA.calls.length).toBe(3);
+ expect(listenerB.calls.length).toBe(2);
- store.dispatch(unknownAction())
- expect(listenerA.calls.length).toBe(4)
- expect(listenerB.calls.length).toBe(2)
- })
+ store.dispatch(unknownAction());
+ expect(listenerA.calls.length).toBe(4);
+ expect(listenerB.calls.length).toBe(2);
+ });
it('only removes listener once when unsubscribe is called', () => {
- const store = createStore(reducers.todos)
- const listenerA = expect.createSpy(() => {})
- const listenerB = expect.createSpy(() => {})
+ const store = createStore(reducers.todos);
+ const listenerA = expect.createSpy(() => {});
+ const listenerB = expect.createSpy(() => {});
- const unsubscribeA = store.subscribe(listenerA)
- store.subscribe(listenerB)
+ const unsubscribeA = store.subscribe(listenerA);
+ store.subscribe(listenerB);
- unsubscribeA()
- unsubscribeA()
+ unsubscribeA();
+ unsubscribeA();
- store.dispatch(unknownAction())
- expect(listenerA.calls.length).toBe(0)
- expect(listenerB.calls.length).toBe(1)
- })
+ store.dispatch(unknownAction());
+ expect(listenerA.calls.length).toBe(0);
+ expect(listenerB.calls.length).toBe(1);
+ });
it('only removes relevant listener when unsubscribe is called', () => {
- const store = createStore(reducers.todos)
- const listener = expect.createSpy(() => {})
+ const store = createStore(reducers.todos);
+ const listener = expect.createSpy(() => {});
- store.subscribe(listener)
- const unsubscribeSecond = store.subscribe(listener)
+ store.subscribe(listener);
+ const unsubscribeSecond = store.subscribe(listener);
- unsubscribeSecond()
- unsubscribeSecond()
+ unsubscribeSecond();
+ unsubscribeSecond();
- store.dispatch(unknownAction())
- expect(listener.calls.length).toBe(1)
- })
+ store.dispatch(unknownAction());
+ expect(listener.calls.length).toBe(1);
+ });
it('supports removing a subscription within a subscription', () => {
- const store = createStore(reducers.todos)
- const listenerA = expect.createSpy(() => {})
- const listenerB = expect.createSpy(() => {})
- const listenerC = expect.createSpy(() => {})
+ const store = createStore(reducers.todos);
+ const listenerA = expect.createSpy(() => {});
+ const listenerB = expect.createSpy(() => {});
+ const listenerC = expect.createSpy(() => {});
- store.subscribe(listenerA)
+ store.subscribe(listenerA);
const unSubB = store.subscribe(() => {
- listenerB()
- unSubB()
- })
- store.subscribe(listenerC)
+ listenerB();
+ unSubB();
+ });
+ store.subscribe(listenerC);
- store.dispatch(unknownAction())
- store.dispatch(unknownAction())
+ store.dispatch(unknownAction());
+ store.dispatch(unknownAction());
- expect(listenerA.calls.length).toBe(2)
- expect(listenerB.calls.length).toBe(1)
- expect(listenerC.calls.length).toBe(2)
- })
+ expect(listenerA.calls.length).toBe(2);
+ expect(listenerB.calls.length).toBe(1);
+ expect(listenerC.calls.length).toBe(2);
+ });
it('delays unsubscribe until the end of current dispatch', () => {
- const store = createStore(reducers.todos)
+ const store = createStore(reducers.todos);
- const unsubscribeHandles = []
+ const unsubscribeHandles = [];
const doUnsubscribeAll = () => unsubscribeHandles.forEach(
unsubscribe => unsubscribe()
- )
+ );
- const listener1 = expect.createSpy(() => {})
- const listener2 = expect.createSpy(() => {})
- const listener3 = expect.createSpy(() => {})
+ const listener1 = expect.createSpy(() => {});
+ const listener2 = expect.createSpy(() => {});
+ const listener3 = expect.createSpy(() => {});
- unsubscribeHandles.push(store.subscribe(() => listener1()))
+ unsubscribeHandles.push(store.subscribe(() => listener1()));
unsubscribeHandles.push(store.subscribe(() => {
- listener2()
- doUnsubscribeAll()
- }))
- unsubscribeHandles.push(store.subscribe(() => listener3()))
-
- store.dispatch(unknownAction())
- expect(listener1.calls.length).toBe(1)
- expect(listener2.calls.length).toBe(1)
- expect(listener3.calls.length).toBe(1)
-
- store.dispatch(unknownAction())
- expect(listener1.calls.length).toBe(1)
- expect(listener2.calls.length).toBe(1)
- expect(listener3.calls.length).toBe(1)
- })
+ listener2();
+ doUnsubscribeAll();
+ }));
+ unsubscribeHandles.push(store.subscribe(() => listener3()));
+
+ store.dispatch(unknownAction());
+ expect(listener1.calls.length).toBe(1);
+ expect(listener2.calls.length).toBe(1);
+ expect(listener3.calls.length).toBe(1);
+
+ store.dispatch(unknownAction());
+ expect(listener1.calls.length).toBe(1);
+ expect(listener2.calls.length).toBe(1);
+ expect(listener3.calls.length).toBe(1);
+ });
it('delays subscribe until the end of current dispatch', () => {
- const store = createStore(reducers.todos)
+ const store = createStore(reducers.todos);
- const listener1 = expect.createSpy(() => {})
- const listener2 = expect.createSpy(() => {})
- const listener3 = expect.createSpy(() => {})
+ const listener1 = expect.createSpy(() => {});
+ const listener2 = expect.createSpy(() => {});
+ const listener3 = expect.createSpy(() => {});
- let listener3Added = false
+ let listener3Added = false;
const maybeAddThirdListener = () => {
if (!listener3Added) {
- listener3Added = true
- store.subscribe(() => listener3())
+ listener3Added = true;
+ store.subscribe(() => listener3());
}
- }
+ };
- store.subscribe(() => listener1())
+ store.subscribe(() => listener1());
store.subscribe(() => {
- listener2()
- maybeAddThirdListener()
- })
+ listener2();
+ maybeAddThirdListener();
+ });
- store.dispatch(unknownAction())
- expect(listener1.calls.length).toBe(1)
- expect(listener2.calls.length).toBe(1)
- expect(listener3.calls.length).toBe(0)
+ store.dispatch(unknownAction());
+ expect(listener1.calls.length).toBe(1);
+ expect(listener2.calls.length).toBe(1);
+ expect(listener3.calls.length).toBe(0);
- store.dispatch(unknownAction())
- expect(listener1.calls.length).toBe(2)
- expect(listener2.calls.length).toBe(2)
- expect(listener3.calls.length).toBe(1)
- })
+ store.dispatch(unknownAction());
+ expect(listener1.calls.length).toBe(2);
+ expect(listener2.calls.length).toBe(2);
+ expect(listener3.calls.length).toBe(1);
+ });
it('uses the last snapshot of subscribers during nested dispatch', () => {
- const store = createStore(reducers.todos)
+ const store = createStore(reducers.todos);
- const listener1 = expect.createSpy(() => {})
- const listener2 = expect.createSpy(() => {})
- const listener3 = expect.createSpy(() => {})
- const listener4 = expect.createSpy(() => {})
+ const listener1 = expect.createSpy(() => {});
+ const listener2 = expect.createSpy(() => {});
+ const listener3 = expect.createSpy(() => {});
+ const listener4 = expect.createSpy(() => {});
- let unsubscribe4
+ let unsubscribe4;
const unsubscribe1 = store.subscribe(() => {
- listener1()
- expect(listener1.calls.length).toBe(1)
- expect(listener2.calls.length).toBe(0)
- expect(listener3.calls.length).toBe(0)
- expect(listener4.calls.length).toBe(0)
-
- unsubscribe1()
- unsubscribe4 = store.subscribe(listener4)
- store.dispatch(unknownAction())
-
- expect(listener1.calls.length).toBe(1)
- expect(listener2.calls.length).toBe(1)
- expect(listener3.calls.length).toBe(1)
- expect(listener4.calls.length).toBe(1)
- })
- store.subscribe(listener2)
- store.subscribe(listener3)
-
- store.dispatch(unknownAction())
- expect(listener1.calls.length).toBe(1)
- expect(listener2.calls.length).toBe(2)
- expect(listener3.calls.length).toBe(2)
- expect(listener4.calls.length).toBe(1)
-
- unsubscribe4()
- store.dispatch(unknownAction())
- expect(listener1.calls.length).toBe(1)
- expect(listener2.calls.length).toBe(3)
- expect(listener3.calls.length).toBe(3)
- expect(listener4.calls.length).toBe(1)
- })
+ listener1();
+ expect(listener1.calls.length).toBe(1);
+ expect(listener2.calls.length).toBe(0);
+ expect(listener3.calls.length).toBe(0);
+ expect(listener4.calls.length).toBe(0);
+
+ unsubscribe1();
+ unsubscribe4 = store.subscribe(listener4);
+ store.dispatch(unknownAction());
+
+ expect(listener1.calls.length).toBe(1);
+ expect(listener2.calls.length).toBe(1);
+ expect(listener3.calls.length).toBe(1);
+ expect(listener4.calls.length).toBe(1);
+ });
+ store.subscribe(listener2);
+ store.subscribe(listener3);
+
+ store.dispatch(unknownAction());
+ expect(listener1.calls.length).toBe(1);
+ expect(listener2.calls.length).toBe(2);
+ expect(listener3.calls.length).toBe(2);
+ expect(listener4.calls.length).toBe(1);
+
+ unsubscribe4();
+ store.dispatch(unknownAction());
+ expect(listener1.calls.length).toBe(1);
+ expect(listener2.calls.length).toBe(3);
+ expect(listener3.calls.length).toBe(3);
+ expect(listener4.calls.length).toBe(1);
+ });
it('provides an up-to-date state when a subscriber is notified', done => {
- const store = createStore(reducers.todos)
+ const store = createStore(reducers.todos);
store.subscribe(() => {
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
- }
- ])
- done()
- })
- store.dispatch(addTodo('Hello'))
- })
+ text: 'Hello',
+ },
+ ]);
+ done();
+ });
+ store.dispatch(addTodo('Hello'));
+ });
it('only accepts plain object actions', () => {
- const store = createStore(reducers.todos)
+ const store = createStore(reducers.todos);
expect(() =>
store.dispatch(unknownAction())
- ).toNotThrow()
+ ).toNotThrow();
function AwesomeMap() { }
- [ null, undefined, 42, 'hey', new AwesomeMap() ].forEach(nonObject =>
+ [null, undefined, 42, 'hey', new AwesomeMap()].forEach(nonObject =>
expect(() =>
store.dispatch(nonObject)
).toThrow(/plain/)
- )
- })
+ );
+ });
it('handles nested dispatches gracefully', () => {
function foo(state = 0, action) {
- return action.type === 'foo' ? 1 : state
+ return action.type === 'foo' ? 1 : state;
}
function bar(state = 0, action) {
- return action.type === 'bar' ? 2 : state
+ return action.type === 'bar' ? 2 : state;
}
- const store = createStore(combineReducers({ foo, bar }))
+ const store = createStore(combineReducers({ foo, bar }));
- store.subscribe(function kindaComponentDidUpdate() {
- const state = store.getState()
+ store.subscribe(() => {
+ const state = store.getState();
if (state.bar === 0) {
- store.dispatch({ type: 'bar' })
+ store.dispatch({ type: 'bar' });
}
- })
+ });
- store.dispatch({ type: 'foo' })
+ store.dispatch({ type: 'foo' });
expect(store.getState()).toEqual({
foo: 1,
- bar: 2
- })
- })
+ bar: 2,
+ });
+ });
it('does not allow dispatch() from within a reducer', () => {
- const store = createStore(reducers.dispatchInTheMiddleOfReducer)
+ const store = createStore(reducers.dispatchInTheMiddleOfReducer);
expect(() =>
store.dispatch(dispatchInMiddle(store.dispatch.bind(store, unknownAction())))
- ).toThrow(/may not dispatch/)
- })
+ ).toThrow(/may not dispatch/);
+ });
it('recovers from an error within a reducer', () => {
- const store = createStore(reducers.errorThrowingReducer)
+ const store = createStore(reducers.errorThrowingReducer);
expect(() =>
store.dispatch(throwError())
- ).toThrow()
+ ).toThrow();
expect(() =>
store.dispatch(unknownAction())
- ).toNotThrow()
- })
+ ).toNotThrow();
+ });
it('throws if action type is missing', () => {
- const store = createStore(reducers.todos)
+ const store = createStore(reducers.todos);
expect(() =>
store.dispatch({})
- ).toThrow(/Actions may not have an undefined "type" property/)
- })
+ ).toThrow(/Actions may not have an undefined "type" property/);
+ });
it('throws if action type is undefined', () => {
- const store = createStore(reducers.todos)
+ const store = createStore(reducers.todos);
expect(() =>
store.dispatch({ type: undefined })
- ).toThrow(/Actions may not have an undefined "type" property/)
- })
+ ).toThrow(/Actions may not have an undefined "type" property/);
+ });
it('does not throw if action type is falsy', () => {
- const store = createStore(reducers.todos)
+ const store = createStore(reducers.todos);
expect(() =>
store.dispatch({ type: false })
- ).toNotThrow()
+ ).toNotThrow();
expect(() =>
store.dispatch({ type: 0 })
- ).toNotThrow()
+ ).toNotThrow();
expect(() =>
store.dispatch({ type: null })
- ).toNotThrow()
+ ).toNotThrow();
expect(() =>
store.dispatch({ type: '' })
- ).toNotThrow()
- })
+ ).toNotThrow();
+ });
it('accepts enhancer as the third argument', () => {
- const emptyArray = []
+ const emptyArray = [];
const spyEnhancer = vanillaCreateStore => (...args) => {
- expect(args[0]).toBe(reducers.todos)
- expect(args[1]).toBe(emptyArray)
- expect(args.length).toBe(2)
- const vanillaStore = vanillaCreateStore(...args)
+ expect(args[0]).toBe(reducers.todos);
+ expect(args[1]).toBe(emptyArray);
+ expect(args.length).toBe(2);
+ const vanillaStore = vanillaCreateStore(...args);
return {
...vanillaStore,
- dispatch: expect.createSpy(vanillaStore.dispatch).andCallThrough()
- }
- }
-
- const store = createStore(reducers.todos, emptyArray, spyEnhancer)
- const action = addTodo('Hello')
- store.dispatch(action)
- expect(store.dispatch).toHaveBeenCalledWith(action)
+ dispatch: expect.createSpy(vanillaStore.dispatch).andCallThrough(),
+ };
+ };
+
+ const store = createStore(reducers.todos, emptyArray, spyEnhancer);
+ const action = addTodo('Hello');
+ store.dispatch(action);
+ expect(store.dispatch).toHaveBeenCalledWith(action);
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
- }
- ])
- })
+ text: 'Hello',
+ },
+ ]);
+ });
it('accepts enhancer as the second argument if initial state is missing', () => {
const spyEnhancer = vanillaCreateStore => (...args) => {
- expect(args[0]).toBe(reducers.todos)
- expect(args[1]).toBe(undefined)
- expect(args.length).toBe(2)
- const vanillaStore = vanillaCreateStore(...args)
+ expect(args[0]).toBe(reducers.todos);
+ expect(args[1]).toBe(undefined);
+ expect(args.length).toBe(2);
+ const vanillaStore = vanillaCreateStore(...args);
return {
...vanillaStore,
- dispatch: expect.createSpy(vanillaStore.dispatch).andCallThrough()
- }
- }
-
- const store = createStore(reducers.todos, spyEnhancer)
- const action = addTodo('Hello')
- store.dispatch(action)
- expect(store.dispatch).toHaveBeenCalledWith(action)
+ dispatch: expect.createSpy(vanillaStore.dispatch).andCallThrough(),
+ };
+ };
+
+ const store = createStore(reducers.todos, spyEnhancer);
+ const action = addTodo('Hello');
+ store.dispatch(action);
+ expect(store.dispatch).toHaveBeenCalledWith(action);
expect(store.getState()).toEqual([
{
id: 1,
- text: 'Hello'
- }
- ])
- })
+ text: 'Hello',
+ },
+ ]);
+ });
it('throws if enhancer is neither undefined nor a function', () => {
expect(() =>
createStore(reducers.todos, undefined, {})
- ).toThrow()
+ ).toThrow();
expect(() =>
createStore(reducers.todos, undefined, [])
- ).toThrow()
+ ).toThrow();
expect(() =>
createStore(reducers.todos, undefined, null)
- ).toThrow()
+ ).toThrow();
expect(() =>
createStore(reducers.todos, undefined, false)
- ).toThrow()
+ ).toThrow();
expect(() =>
createStore(reducers.todos, undefined, undefined)
- ).toNotThrow()
+ ).toNotThrow();
expect(() =>
createStore(reducers.todos, undefined, x => x)
- ).toNotThrow()
+ ).toNotThrow();
expect(() =>
createStore(reducers.todos, x => x)
- ).toNotThrow()
+ ).toNotThrow();
expect(() =>
createStore(reducers.todos, [])
- ).toNotThrow()
+ ).toNotThrow();
expect(() =>
createStore(reducers.todos, {})
- ).toNotThrow()
- })
+ ).toNotThrow();
+ });
it('throws if nextReducer is not a function', () => {
- const store = createStore(reducers.todos)
+ const store = createStore(reducers.todos);
expect(() =>
store.replaceReducer()
- ).toThrow('Expected the nextReducer to be a function.')
+ ).toThrow('Expected the nextReducer to be a function.');
expect(() =>
store.replaceReducer(() => {})
- ).toNotThrow()
- })
+ ).toNotThrow();
+ });
it('throws if listener is not a function', () => {
- const store = createStore(reducers.todos)
+ const store = createStore(reducers.todos);
expect(() =>
store.subscribe()
- ).toThrow()
+ ).toThrow();
expect(() =>
store.subscribe('')
- ).toThrow()
+ ).toThrow();
expect(() =>
store.subscribe(null)
- ).toThrow()
+ ).toThrow();
expect(() =>
store.subscribe(undefined)
- ).toThrow()
- })
-})
+ ).toThrow();
+ });
+});
diff --git a/test/helpers/actionCreators.js b/test/helpers/actionCreators.js
index 198f61be20..41c0ca5c81 100644
--- a/test/helpers/actionCreators.js
+++ b/test/helpers/actionCreators.js
@@ -1,39 +1,39 @@
-import { ADD_TODO, DISPATCH_IN_MIDDLE, THROW_ERROR, UNKNOWN_ACTION } from './actionTypes'
+import { ADD_TODO, DISPATCH_IN_MIDDLE, THROW_ERROR, UNKNOWN_ACTION } from './actionTypes';
export function addTodo(text) {
- return { type: ADD_TODO, text }
+ return { type: ADD_TODO, text };
}
export function addTodoAsync(text) {
return dispatch => new Promise(resolve => setImmediate(() => {
- dispatch(addTodo(text))
- resolve()
- }))
+ dispatch(addTodo(text));
+ resolve();
+ }));
}
export function addTodoIfEmpty(text) {
return (dispatch, getState) => {
if (!getState().length) {
- dispatch(addTodo(text))
+ dispatch(addTodo(text));
}
- }
+ };
}
export function dispatchInMiddle(boundDispatchFn) {
return {
type: DISPATCH_IN_MIDDLE,
- boundDispatchFn
- }
+ boundDispatchFn,
+ };
}
export function throwError() {
return {
- type: THROW_ERROR
- }
+ type: THROW_ERROR,
+ };
}
export function unknownAction() {
return {
- type: UNKNOWN_ACTION
- }
+ type: UNKNOWN_ACTION,
+ };
}
diff --git a/test/helpers/actionTypes.js b/test/helpers/actionTypes.js
index 00092962f2..b76ec8a162 100644
--- a/test/helpers/actionTypes.js
+++ b/test/helpers/actionTypes.js
@@ -1,4 +1,4 @@
-export const ADD_TODO = 'ADD_TODO'
-export const DISPATCH_IN_MIDDLE = 'DISPATCH_IN_MIDDLE'
-export const THROW_ERROR = 'THROW_ERROR'
-export const UNKNOWN_ACTION = 'UNKNOWN_ACTION'
+export const ADD_TODO = 'ADD_TODO';
+export const DISPATCH_IN_MIDDLE = 'DISPATCH_IN_MIDDLE';
+export const THROW_ERROR = 'THROW_ERROR';
+export const UNKNOWN_ACTION = 'UNKNOWN_ACTION';
diff --git a/test/helpers/middleware.js b/test/helpers/middleware.js
index 945f412cc9..6174654f30 100644
--- a/test/helpers/middleware.js
+++ b/test/helpers/middleware.js
@@ -1,6 +1,7 @@
export function thunk({ dispatch, getState }) {
- return next => action =>
+ return next => action => (
typeof action === 'function' ?
action(dispatch, getState) :
next(action)
+ );
}
diff --git a/test/helpers/reducers.js b/test/helpers/reducers.js
index 8e9c7321ec..7d5f32672d 100644
--- a/test/helpers/reducers.js
+++ b/test/helpers/reducers.js
@@ -1,24 +1,24 @@
-import { ADD_TODO, DISPATCH_IN_MIDDLE, THROW_ERROR } from './actionTypes'
+import { ADD_TODO, DISPATCH_IN_MIDDLE, THROW_ERROR } from './actionTypes';
function id(state = []) {
return state.reduce((result, item) => (
item.id > result ? item.id : result
- ), 0) + 1
+ ), 0) + 1;
}
export function todos(state = [], action) {
switch (action.type) {
case ADD_TODO:
- return [
- ...state,
+ return [
+ ...state,
{
id: id(state),
- text: action.text
- }
- ]
+ text: action.text,
+ },
+ ];
default:
- return state
+ return state;
}
}
@@ -28,29 +28,29 @@ export function todosReverse(state = [], action) {
return [
{
id: id(state),
- text: action.text
- }, ...state
- ]
+ text: action.text,
+ }, ...state,
+ ];
default:
- return state
+ return state;
}
}
export function dispatchInTheMiddleOfReducer(state = [], action) {
switch (action.type) {
case DISPATCH_IN_MIDDLE:
- action.boundDispatchFn()
- return state
+ action.boundDispatchFn();
+ return state;
default:
- return state
+ return state;
}
}
export function errorThrowingReducer(state = [], action) {
switch (action.type) {
case THROW_ERROR:
- throw new Error()
+ throw new Error();
default:
- return state
+ return state;
}
}
diff --git a/test/typescript.spec.js b/test/typescript.spec.js
index 5d0bc28f0c..33ed9acc5e 100644
--- a/test/typescript.spec.js
+++ b/test/typescript.spec.js
@@ -1,14 +1,14 @@
-import * as tt from 'typescript-definition-tester'
+import * as tt from 'typescript-definition-tester';
-describe('TypeScript definitions', function () {
- this.timeout(0)
+describe('TypeScript definitions', () => {
+ this.timeout(0);
it('should compile against index.d.ts', (done) => {
tt.compileDirectory(
- __dirname + '/typescript',
+ `${__dirname}/typescript`,
fileName => fileName.match(/\.ts$/),
() => done()
- )
- })
-})
+ );
+ });
+});
diff --git a/test/utils/warning.spec.js b/test/utils/warning.spec.js
index e8e1316340..eb47a50ebd 100644
--- a/test/utils/warning.spec.js
+++ b/test/utils/warning.spec.js
@@ -1,36 +1,36 @@
-import expect from 'expect'
-import warning from '../../src/utils/warning'
+import expect from 'expect';
+import warning from '../../src/utils/warning';
describe('Utils', () => {
describe('warning', () => {
it('calls console.error when available', () => {
- const spy = expect.spyOn(console, 'error')
+ const spy = expect.spyOn(console, 'error');
try {
- warning('Test')
- expect(spy.calls[0].arguments[0]).toBe('Test')
+ warning('Test');
+ expect(spy.calls[0].arguments[0]).toBe('Test');
} finally {
- spy.restore()
+ spy.restore();
}
- })
+ });
it('does not throw when console.error is not available', () => {
- const realConsole = global.console
- Object.defineProperty(global, 'console', { value: {} })
+ const realConsole = global.console;
+ Object.defineProperty(global, 'console', { value: {} });
try {
- expect(() => warning('Test')).toNotThrow()
+ expect(() => warning('Test')).toNotThrow();
} finally {
- Object.defineProperty(global, 'console', { value: realConsole })
+ Object.defineProperty(global, 'console', { value: realConsole });
}
- })
+ });
it('does not throw when console is not available', () => {
- const realConsole = global.console
- Object.defineProperty(global, 'console', { value: undefined })
+ const realConsole = global.console;
+ Object.defineProperty(global, 'console', { value: undefined });
try {
- expect(() => warning('Test')).toNotThrow()
+ expect(() => warning('Test')).toNotThrow();
} finally {
- Object.defineProperty(global, 'console', { value: realConsole })
+ Object.defineProperty(global, 'console', { value: realConsole });
}
- })
- })
-})
+ });
+ });
+});
From e5064f3aa3bd030b73076e06e7139d05eaeabbb8 Mon Sep 17 00:00:00 2001
From: Mateusz Zatorski
Date: Thu, 31 Mar 2016 01:46:16 +0100
Subject: [PATCH 2/4] oops, didn't mean to delete the /build
---
build/es3ify.js | 25 +++++++++++++++++++
build/use-lodash-es.js | 10 ++++++++
.../counter/test/components/Counter.spec.js | 2 +-
3 files changed, 36 insertions(+), 1 deletion(-)
create mode 100644 build/es3ify.js
create mode 100644 build/use-lodash-es.js
diff --git a/build/es3ify.js b/build/es3ify.js
new file mode 100644
index 0000000000..f4639cf400
--- /dev/null
+++ b/build/es3ify.js
@@ -0,0 +1,25 @@
+var glob = require('glob')
+var fs = require('fs')
+var es3ify = require('es3ify')
+
+glob('./@(lib|dist|es)/**/*.js', function (err, files) {
+ if (err) {
+ throw err
+ }
+
+ files.forEach(function (file) {
+ fs.readFile(file, 'utf8', function (err, data) {
+ if (err) {
+ throw err
+ }
+
+ fs.writeFile(file, es3ify.transform(data), function (err) {
+ if (err) {
+ throw err
+ }
+
+ console.log('es3ified ' + file) // eslint-disable-line no-console
+ })
+ })
+ })
+})
diff --git a/build/use-lodash-es.js b/build/use-lodash-es.js
new file mode 100644
index 0000000000..ba4f2f52e6
--- /dev/null
+++ b/build/use-lodash-es.js
@@ -0,0 +1,10 @@
+module.exports = function () {
+ return {
+ visitor: {
+ ImportDeclaration(path) {
+ var source = path.node.source
+ source.value = source.value.replace(/^lodash($|\/)/, 'lodash-es$1')
+ }
+ }
+ }
+}
diff --git a/examples/counter/test/components/Counter.spec.js b/examples/counter/test/components/Counter.spec.js
index 7474bd5b4d..874d835136 100644
--- a/examples/counter/test/components/Counter.spec.js
+++ b/examples/counter/test/components/Counter.spec.js
@@ -6,7 +6,7 @@ import Counter from '../../components/Counter';
function setup(value = 0) {
const actions = {
onIncrement: expect.createSpy(),
- onDecrement: expect.createSpy()
+ onDecrement: expect.createSpy(),
};
const component = shallow(
From e59eceb89706878739b9833803dd983cef7619b6 Mon Sep 17 00:00:00 2001
From: Mateusz Zatorski
Date: Thu, 31 Mar 2016 03:06:35 +0100
Subject: [PATCH 3/4] refactor examples to pure components, fix more lint err
---
examples/async/components/Picker.js | 40 ++++++-------
examples/async/components/Posts.js | 22 ++++----
examples/real-world/components/List.js | 5 +-
examples/real-world/components/Repo.js | 48 ++++++++--------
examples/real-world/components/User.js | 32 +++++------
examples/real-world/containers/DevTools.js | 4 +-
examples/real-world/containers/Root.dev.js | 25 ++++-----
examples/real-world/containers/Root.prod.js | 19 +++----
examples/shopping-cart/actions/index.js | 2 +-
examples/shopping-cart/components/Cart.js | 56 +++++++++----------
examples/shopping-cart/components/Product.js | 13 ++---
.../shopping-cart/components/ProductItem.js | 32 +++++------
.../shopping-cart/components/ProductsList.js | 20 +++----
examples/shopping-cart/containers/App.js | 26 ++++-----
.../shopping-cart/containers/CartContainer.js | 24 ++++----
.../containers/ProductsContainer.js | 32 +++++------
examples/testAll.js | 14 ++---
examples/todomvc/components/Footer.js | 2 +
examples/todomvc/components/Header.js | 7 ++-
examples/todomvc/components/MainSection.js | 4 ++
examples/todomvc/containers/App.js | 19 +++----
.../todomvc/test/components/Footer.spec.js | 6 +-
examples/todos-with-undo/components/Link.js | 26 ++++-----
.../containers/VisibleTodoList.js | 2 +
examples/todos/components/Link.js | 26 ++++-----
examples/todos/containers/VisibleTodoList.js | 2 +
.../universal/common/components/Counter.js | 33 +++++------
27 files changed, 249 insertions(+), 292 deletions(-)
diff --git a/examples/async/components/Picker.js b/examples/async/components/Picker.js
index e9481f0486..66b2292f7c 100644
--- a/examples/async/components/Picker.js
+++ b/examples/async/components/Picker.js
@@ -1,26 +1,20 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
-export default class Picker extends Component {
- render() {
- const { value, onChange, options } = this.props;
-
- return (
-
- {value}
- onChange(e.target.value)}
- value={value}
- >
- {options.map(option =>
-
- {option}
- )
- }
-
-
- );
- }
-}
+const Picker = ({ value, onChange, options }) => (
+
+ {value}
+ onChange(e.target.value)}
+ value={value}
+ >
+ {options.map(option =>
+
+ {option}
+ )
+ }
+
+
+);
Picker.propTypes = {
options: PropTypes.arrayOf(
@@ -29,3 +23,5 @@ Picker.propTypes = {
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
};
+
+export default Picker;
diff --git a/examples/async/components/Posts.js b/examples/async/components/Posts.js
index 2b4a7d0b52..d99ab58a37 100644
--- a/examples/async/components/Posts.js
+++ b/examples/async/components/Posts.js
@@ -1,17 +1,15 @@
-import React, { PropTypes, Component } from 'react';
+import React, { PropTypes } from 'react';
-export default class Posts extends Component {
- render() {
- return (
-
- {this.props.posts.map((post, i) =>
- {post.title}
- )}
-
- );
- }
-}
+const Posts = ({ posts }) => (
+
+ {posts.map((post, i) =>
+ {post.title}
+ )}
+
+);
Posts.propTypes = {
posts: PropTypes.array.isRequired,
};
+
+export default Posts;
diff --git a/examples/real-world/components/List.js b/examples/real-world/components/List.js
index 306a6b03fa..0fdb7df2e8 100644
--- a/examples/real-world/components/List.js
+++ b/examples/real-world/components/List.js
@@ -4,10 +4,7 @@ export default class List extends Component {
renderLoadMore() {
const { isFetching, onLoadMoreClick } = this.props;
return (
-
+
{isFetching ? 'Loading...' : 'Load More'}
);
diff --git a/examples/real-world/components/Repo.js b/examples/real-world/components/Repo.js
index 480b9932e6..7503bf96c2 100644
--- a/examples/real-world/components/Repo.js
+++ b/examples/real-world/components/Repo.js
@@ -1,31 +1,27 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
import { Link } from 'react-router';
-export default class Repo extends Component {
+const Repo = ({ repo, owner }) => {
+ const { login } = owner;
+ const { name, description } = repo;
- render() {
- const { repo, owner } = this.props;
- const { login } = owner;
- const { name, description } = repo;
-
- return (
-
-
-
- {name}
-
- {' by '}
-
- {login}
-
-
- {description &&
-
{description}
- }
-
- );
- }
-}
+ return (
+
+
+
+ {name}
+
+ {' by '}
+
+ {login}
+
+
+ {description &&
+
{description}
+ }
+
+ );
+};
Repo.propTypes = {
repo: PropTypes.shape({
@@ -36,3 +32,5 @@ Repo.propTypes = {
login: PropTypes.string.isRequired,
}).isRequired,
};
+
+export default Repo;
diff --git a/examples/real-world/components/User.js b/examples/real-world/components/User.js
index 455b9942c8..f7a8086c56 100644
--- a/examples/real-world/components/User.js
+++ b/examples/real-world/components/User.js
@@ -1,22 +1,20 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
import { Link } from 'react-router';
-export default class User extends Component {
- render() {
- const { login, avatarUrl, name } = this.props.user;
+const User = ({ user }) => {
+ const { login, avatarUrl, name } = user;
- return (
-
-
-
-
- {login} {name && ({name}) }
-
-
-
- );
- }
-}
+ return (
+
+
+
+
+ {login} {name && ({name}) }
+
+
+
+ );
+};
User.propTypes = {
user: PropTypes.shape({
@@ -25,3 +23,5 @@ User.propTypes = {
name: PropTypes.string,
}).isRequired,
};
+
+export default User;
diff --git a/examples/real-world/containers/DevTools.js b/examples/real-world/containers/DevTools.js
index 64e9a71a2e..caee0a21eb 100644
--- a/examples/real-world/containers/DevTools.js
+++ b/examples/real-world/containers/DevTools.js
@@ -4,9 +4,7 @@ import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
-
+
);
diff --git a/examples/real-world/containers/Root.dev.js b/examples/real-world/containers/Root.dev.js
index d8e53750c2..d8e98bd930 100644
--- a/examples/real-world/containers/Root.dev.js
+++ b/examples/real-world/containers/Root.dev.js
@@ -1,24 +1,21 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
import { Provider } from 'react-redux';
import routes from '../routes';
import DevTools from './DevTools';
import { Router } from 'react-router';
-export default class Root extends Component {
- render() {
- const { store, history } = this.props;
- return (
-
-
-
-
-
-
- );
- }
-}
+const Root = ({ store, history }) => (
+
+
+
+
+
+
+);
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
};
+
+export default Root;
diff --git a/examples/real-world/containers/Root.prod.js b/examples/real-world/containers/Root.prod.js
index 44d81717f1..a73e45369a 100644
--- a/examples/real-world/containers/Root.prod.js
+++ b/examples/real-world/containers/Root.prod.js
@@ -1,20 +1,17 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
import { Provider } from 'react-redux';
import routes from '../routes';
import { Router } from 'react-router';
-export default class Root extends Component {
- render() {
- const { store, history } = this.props;
- return (
-
-
-
- );
- }
-}
+const Root = ({ store, history }) => (
+
+
+
+);
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
};
+
+export default Root;
diff --git a/examples/shopping-cart/actions/index.js b/examples/shopping-cart/actions/index.js
index 701ff3c506..b3b0da59d3 100644
--- a/examples/shopping-cart/actions/index.js
+++ b/examples/shopping-cart/actions/index.js
@@ -4,7 +4,7 @@ import * as types from '../constants/ActionTypes';
function receiveProducts(products) {
return {
type: types.RECEIVE_PRODUCTS,
- products: products,
+ products,
};
}
diff --git a/examples/shopping-cart/components/Cart.js b/examples/shopping-cart/components/Cart.js
index e59e794e51..73c04336fd 100644
--- a/examples/shopping-cart/components/Cart.js
+++ b/examples/shopping-cart/components/Cart.js
@@ -1,39 +1,35 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
import Product from './Product';
-export default class Cart extends Component {
- render() {
- const { products, total, onCheckoutClicked } = this.props;
+const Cart = ({ products, total, onCheckoutClicked }) => {
+ const hasProducts = products.length > 0;
+ const nodes = !hasProducts ?
+ Please add some products to cart. :
+ products.map(product =>
+
+ );
- const hasProducts = products.length > 0;
- const nodes = !hasProducts ?
- Please add some products to cart. :
- products.map(product =>
-
- );
-
- return (
-
-
Your Cart
-
{nodes}
-
Total: ${total}
-
- Checkout
-
-
- );
- }
-}
+ return (
+
+
Your Cart
+
{nodes}
+
Total: ${total}
+
+ Checkout
+
+
+ );
+};
Cart.propTypes = {
products: PropTypes.array,
total: PropTypes.string,
onCheckoutClicked: PropTypes.func,
};
+
+export default Cart;
diff --git a/examples/shopping-cart/components/Product.js b/examples/shopping-cart/components/Product.js
index e766050bd4..e0a9f592ae 100644
--- a/examples/shopping-cart/components/Product.js
+++ b/examples/shopping-cart/components/Product.js
@@ -1,14 +1,13 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
-export default class Product extends Component {
- render() {
- const { price, quantity, title } = this.props;
- return {title} - ${price} {quantity ? `x ${quantity}` : null}
;
- }
-}
+const Product = ({ price, quantity, title }) => (
+ {title} - ${price} {quantity ? `x ${quantity}` : null}
+);
Product.propTypes = {
price: PropTypes.number,
quantity: PropTypes.number,
title: PropTypes.string,
};
+
+export default Product;
diff --git a/examples/shopping-cart/components/ProductItem.js b/examples/shopping-cart/components/ProductItem.js
index 544edd5f7e..bc06f1d904 100644
--- a/examples/shopping-cart/components/ProductItem.js
+++ b/examples/shopping-cart/components/ProductItem.js
@@ -1,23 +1,17 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
import Product from './Product';
-export default class ProductItem extends Component {
- render() {
- const { product } = this.props;
-
- return (
-
-
-
0 ? '' : 'disabled'}
- >
- {product.inventory > 0 ? 'Add to cart' : 'Sold Out'}
-
-
- );
- }
-}
+const ProductItem = ({ product }) => (
+
+
+
0 ? '' : 'disabled'}
+ >
+ {product.inventory > 0 ? 'Add to cart' : 'Sold Out'}
+
+
+);
ProductItem.propTypes = {
product: PropTypes.shape({
@@ -27,3 +21,5 @@ ProductItem.propTypes = {
}).isRequired,
onAddToCartClicked: PropTypes.func.isRequired,
};
+
+export default ProductItem;
diff --git a/examples/shopping-cart/components/ProductsList.js b/examples/shopping-cart/components/ProductsList.js
index 229a6e501a..e437051772 100644
--- a/examples/shopping-cart/components/ProductsList.js
+++ b/examples/shopping-cart/components/ProductsList.js
@@ -1,17 +1,15 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
-export default class ProductsList extends Component {
- render() {
- return (
-
-
{this.props.title}
-
{this.props.children}
-
- );
- }
-}
+const ProductsList = ({ title, children }) => (
+
+);
ProductsList.propTypes = {
children: PropTypes.node,
title: PropTypes.string.isRequired,
};
+
+export default ProductsList;
diff --git a/examples/shopping-cart/containers/App.js b/examples/shopping-cart/containers/App.js
index e3eb99248c..89d300bf37 100644
--- a/examples/shopping-cart/containers/App.js
+++ b/examples/shopping-cart/containers/App.js
@@ -1,17 +1,15 @@
-import React, { Component } from 'react';
+import React from 'react';
import ProductsContainer from './ProductsContainer';
import CartContainer from './CartContainer';
-export default class App extends Component {
- render() {
- return (
-
-
Shopping Cart Example
-
-
-
-
-
- );
- }
-}
+const App = () => (
+
+
Shopping Cart Example
+
+
+
+
+
+);
+
+export default App;
diff --git a/examples/shopping-cart/containers/CartContainer.js b/examples/shopping-cart/containers/CartContainer.js
index bc911f4847..3eaab92ba8 100644
--- a/examples/shopping-cart/containers/CartContainer.js
+++ b/examples/shopping-cart/containers/CartContainer.js
@@ -1,22 +1,20 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { checkout } from '../actions';
import { getTotal, getCartProducts } from '../reducers';
import Cart from '../components/Cart';
-class CartContainer extends Component {
- render() {
- const { products, total } = this.props;
+const CartContainer = (props) => {
+ const { products, total } = props;
- return (
- this.props.checkout()}
- />
- );
- }
-}
+ return (
+ props.checkout()}
+ />
+ );
+};
CartContainer.propTypes = {
products: PropTypes.arrayOf(PropTypes.shape({
diff --git a/examples/shopping-cart/containers/ProductsContainer.js b/examples/shopping-cart/containers/ProductsContainer.js
index c54660177d..98f074c3d8 100644
--- a/examples/shopping-cart/containers/ProductsContainer.js
+++ b/examples/shopping-cart/containers/ProductsContainer.js
@@ -1,26 +1,24 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { addToCart } from '../actions';
import { getVisibleProducts } from '../reducers/products';
import ProductItem from '../components/ProductItem';
import ProductsList from '../components/ProductsList';
-class ProductsContainer extends Component {
- render() {
- const { products } = this.props;
- return (
-
- {products.map(product =>
- this.props.addToCart(product.id)}
- />
- )}
-
- );
- }
-}
+const ProductsContainer = (props) => {
+ const { products } = props;
+ return (
+
+ {products.map(product =>
+ props.addToCart(product.id)}
+ />
+ )}
+
+ );
+};
ProductsContainer.propTypes = {
products: PropTypes.arrayOf(PropTypes.shape({
diff --git a/examples/testAll.js b/examples/testAll.js
index 7763f680c3..fe696865bb 100644
--- a/examples/testAll.js
+++ b/examples/testAll.js
@@ -6,14 +6,14 @@ import fs from 'fs';
import path from 'path';
import { spawnSync } from 'child_process';
-var exampleDirs = fs.readdirSync(__dirname).filter((file) => {
- return fs.statSync(path.join(__dirname, file)).isDirectory();
-});
+const exampleDirs = fs.readdirSync(__dirname).filter((file) => (
+ fs.statSync(path.join(__dirname, file)).isDirectory()
+));
// Ordering is important here. `npm install` must come first.
-var cmdArgs = [
+const cmdArgs = [
{ cmd: 'npm', args: ['install'] },
- { cmd: 'npm', args: ['test'] }
+ { cmd: 'npm', args: ['test'] },
];
for (const dir of exampleDirs) {
@@ -21,12 +21,12 @@ for (const dir of exampleDirs) {
// declare opts in this scope to avoid https://github.com/joyent/node/issues/9158
const opts = {
cwd: path.join(__dirname, dir),
- stdio: 'inherit'
+ stdio: 'inherit',
};
let result = {};
if (process.platform === 'win32') {
- result = spawnSync(cmdArg.cmd + '.cmd', cmdArg.args, opts);
+ result = spawnSync(`${cmdArg.cmd}.cmd`, cmdArg.args, opts);
} else {
result = spawnSync(cmdArg.cmd, cmdArg.args, opts);
}
diff --git a/examples/todomvc/components/Footer.js b/examples/todomvc/components/Footer.js
index 6d1cfb6824..c18aae0e50 100644
--- a/examples/todomvc/components/Footer.js
+++ b/examples/todomvc/components/Footer.js
@@ -43,6 +43,8 @@ class Footer extends Component {
);
}
+
+ return null;
}
render() {
diff --git a/examples/todomvc/components/Header.js b/examples/todomvc/components/Header.js
index 6390b10dc7..d4aeb99ef6 100644
--- a/examples/todomvc/components/Header.js
+++ b/examples/todomvc/components/Header.js
@@ -2,6 +2,11 @@ import React, { PropTypes, Component } from 'react';
import TodoTextInput from './TodoTextInput';
class Header extends Component {
+ constructor() {
+ super();
+ this.handleSave = this.handleSave.bind(this);
+ }
+
handleSave(text) {
if (text.length !== 0) {
this.props.addTodo(text);
@@ -13,7 +18,7 @@ class Header extends Component {
diff --git a/examples/todomvc/components/MainSection.js b/examples/todomvc/components/MainSection.js
index 5d38cbf41d..65cbb65a72 100644
--- a/examples/todomvc/components/MainSection.js
+++ b/examples/todomvc/components/MainSection.js
@@ -36,6 +36,8 @@ class MainSection extends Component {
/>
);
}
+
+ return null;
}
renderFooter(completedCount) {
@@ -53,6 +55,8 @@ class MainSection extends Component {
/>
);
}
+
+ return null;
}
render() {
diff --git a/examples/todomvc/containers/App.js b/examples/todomvc/containers/App.js
index 28392fc323..8086d6dbdd 100644
--- a/examples/todomvc/containers/App.js
+++ b/examples/todomvc/containers/App.js
@@ -1,21 +1,16 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions';
-class App extends Component {
- render() {
- const { todos, actions } = this.props;
- return (
-
-
-
-
- );
- }
-}
+const App = ({ todos, actions }) => (
+
+
+
+
+);
App.propTypes = {
todos: PropTypes.array.isRequired,
diff --git a/examples/todomvc/test/components/Footer.spec.js b/examples/todomvc/test/components/Footer.spec.js
index 6b43d290c0..6176d360a7 100644
--- a/examples/todomvc/test/components/Footer.spec.js
+++ b/examples/todomvc/test/components/Footer.spec.js
@@ -27,10 +27,10 @@ function getTextContent(elem) {
const children = Array.isArray(elem.props.children) ?
elem.props.children : [elem.props.children];
- return children.reduce((out, child) => {
+ return children.reduce((out, child) => (
// Children are either elements or text strings
- return out + (child.props ? getTextContent(child) : child);
- }, '');
+ out + (child.props ? getTextContent(child) : child)
+ ), '');
}
describe('components', () => {
diff --git a/examples/todos-with-undo/components/Link.js b/examples/todos-with-undo/components/Link.js
index 71bcabda8a..e48d6c67a0 100644
--- a/examples/todos-with-undo/components/Link.js
+++ b/examples/todos-with-undo/components/Link.js
@@ -1,21 +1,15 @@
import React, { PropTypes } from 'react';
-const Link = ({ active, children, onClick }) => {
- if (active) {
- return {children} ;
- }
-
- return (
- {
- e.preventDefault();
- onClick();
- }}
- >
- {children}
-
- );
-};
+const Link = ({ active, children, onClick }) => (
+ {
+ e.preventDefault();
+ onClick();
+ }}
+ >
+ { active ? {children} : null }
+
+);
Link.propTypes = {
active: PropTypes.bool.isRequired,
diff --git a/examples/todos-with-undo/containers/VisibleTodoList.js b/examples/todos-with-undo/containers/VisibleTodoList.js
index b97193b8c6..2b4583d5a3 100644
--- a/examples/todos-with-undo/containers/VisibleTodoList.js
+++ b/examples/todos-with-undo/containers/VisibleTodoList.js
@@ -10,6 +10,8 @@ const getVisibleTodos = (todos, filter) => {
return todos.filter(t => t.completed);
case 'SHOW_ACTIVE':
return todos.filter(t => !t.completed);
+ default:
+ return todos;
}
};
diff --git a/examples/todos/components/Link.js b/examples/todos/components/Link.js
index 71bcabda8a..e48d6c67a0 100644
--- a/examples/todos/components/Link.js
+++ b/examples/todos/components/Link.js
@@ -1,21 +1,15 @@
import React, { PropTypes } from 'react';
-const Link = ({ active, children, onClick }) => {
- if (active) {
- return {children} ;
- }
-
- return (
- {
- e.preventDefault();
- onClick();
- }}
- >
- {children}
-
- );
-};
+const Link = ({ active, children, onClick }) => (
+ {
+ e.preventDefault();
+ onClick();
+ }}
+ >
+ { active ? {children} : null }
+
+);
Link.propTypes = {
active: PropTypes.bool.isRequired,
diff --git a/examples/todos/containers/VisibleTodoList.js b/examples/todos/containers/VisibleTodoList.js
index a045f313cd..75c054ea94 100644
--- a/examples/todos/containers/VisibleTodoList.js
+++ b/examples/todos/containers/VisibleTodoList.js
@@ -10,6 +10,8 @@ const getVisibleTodos = (todos, filter) => {
return todos.filter(t => t.completed);
case 'SHOW_ACTIVE':
return todos.filter(t => !t.completed);
+ default:
+ return todos;
}
};
diff --git a/examples/universal/common/components/Counter.js b/examples/universal/common/components/Counter.js
index 0823e71f95..372e8b35a3 100644
--- a/examples/universal/common/components/Counter.js
+++ b/examples/universal/common/components/Counter.js
@@ -1,23 +1,18 @@
-import React, { Component, PropTypes } from 'react';
+import React, { PropTypes } from 'react';
-class Counter extends Component {
- render() {
- const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props;
- return (
-
- Clicked: {counter} times
- {' '}
- +
- {' '}
- -
- {' '}
- Increment if odd
- {' '}
- incrementAsync()}>Increment async
-
- );
- }
-}
+const Counter = ({ increment, incrementIfOdd, incrementAsync, decrement, counter }) => (
+
+ Clicked: {counter} times
+ {' '}
+ +
+ {' '}
+ -
+ {' '}
+ Increment if odd
+ {' '}
+ incrementAsync()}>Increment async
+
+);
Counter.propTypes = {
increment: PropTypes.func.isRequired,
From 8b7dded8e094d6b1fc877471489815045c1979b2 Mon Sep 17 00:00:00 2001
From: Mateusz Zatorski
Date: Thu, 31 Mar 2016 13:43:04 +0100
Subject: [PATCH 4/4] fixed the rest linting errors
---
build/es3ify.js | 34 +++++++++----------
build/use-lodash-es.js | 14 ++++----
examples/async/actions/index.js | 1 +
examples/async/containers/App.js | 9 +++--
.../shopping-cart/components/ProductItem.js | 4 +--
examples/shopping-cart/reducers/products.js | 5 +--
examples/todomvc/components/MainSection.js | 5 ++-
.../todomvc/test/components/Footer.spec.js | 2 +-
examples/tree-view/reducers/index.js | 2 +-
src/bindActionCreators.js | 3 +-
src/combineReducers.js | 11 +++---
src/createStore.js | 14 ++++----
test/typescript.spec.js | 3 +-
13 files changed, 55 insertions(+), 52 deletions(-)
diff --git a/build/es3ify.js b/build/es3ify.js
index f4639cf400..e7b501c163 100644
--- a/build/es3ify.js
+++ b/build/es3ify.js
@@ -1,25 +1,25 @@
-var glob = require('glob')
-var fs = require('fs')
-var es3ify = require('es3ify')
+const glob = require('glob');
+const fs = require('fs');
+const es3ify = require('es3ify');
-glob('./@(lib|dist|es)/**/*.js', function (err, files) {
+glob('./@(lib|dist|es)/**/*.js', (err, files) => {
if (err) {
- throw err
+ throw err;
}
- files.forEach(function (file) {
- fs.readFile(file, 'utf8', function (err, data) {
- if (err) {
- throw err
+ files.forEach((file) => {
+ fs.readFile(file, 'utf8', (error, data) => {
+ if (error) {
+ throw error;
}
- fs.writeFile(file, es3ify.transform(data), function (err) {
- if (err) {
- throw err
+ fs.writeFile(file, es3ify.transform(data), (writeErr) => {
+ if (writeErr) {
+ throw writeErr;
}
- console.log('es3ified ' + file) // eslint-disable-line no-console
- })
- })
- })
-})
+ console.log(`es3ified ${file}`); // eslint-disable-line no-console
+ });
+ });
+ });
+});
diff --git a/build/use-lodash-es.js b/build/use-lodash-es.js
index ba4f2f52e6..2f3876ce47 100644
--- a/build/use-lodash-es.js
+++ b/build/use-lodash-es.js
@@ -1,10 +1,10 @@
-module.exports = function () {
+module.exports = function useLodashEs() {
return {
visitor: {
ImportDeclaration(path) {
- var source = path.node.source
- source.value = source.value.replace(/^lodash($|\/)/, 'lodash-es$1')
- }
- }
- }
-}
+ const source = path.node.source;
+ source.value = source.value.replace(/^lodash($|\/)/, 'lodash-es$1');
+ },
+ },
+ };
+};
diff --git a/examples/async/actions/index.js b/examples/async/actions/index.js
index f8ba98a1c6..c6cafd23eb 100644
--- a/examples/async/actions/index.js
+++ b/examples/async/actions/index.js
@@ -60,5 +60,6 @@ export function fetchPostsIfNeeded(reddit) {
if (shouldFetchPosts(getState(), reddit)) {
return dispatch(fetchPosts(reddit));
}
+ return null;
};
}
diff --git a/examples/async/containers/App.js b/examples/async/containers/App.js
index 2d8568eade..f4791c7162 100644
--- a/examples/async/containers/App.js
+++ b/examples/async/containers/App.js
@@ -38,6 +38,7 @@ class App extends Component {
render() {
const { selectedReddit, posts, isFetching, lastUpdated } = this.props;
const isEmpty = posts.length === 0;
+ const message = isFetching ? Loading... : Empty. ;
return (
}
- {isEmpty
- ? (isFetching ? Loading... : Empty. )
- :
+ {isEmpty ? message :
}
);
diff --git a/examples/shopping-cart/components/ProductItem.js b/examples/shopping-cart/components/ProductItem.js
index bc06f1d904..c473323159 100644
--- a/examples/shopping-cart/components/ProductItem.js
+++ b/examples/shopping-cart/components/ProductItem.js
@@ -1,11 +1,11 @@
import React, { PropTypes } from 'react';
import Product from './Product';
-const ProductItem = ({ product }) => (
+const ProductItem = ({ product, onAddToCartClicked }) => (
0 ? '' : 'disabled'}
>
{product.inventory > 0 ? 'Add to cart' : 'Sold Out'}
diff --git a/examples/shopping-cart/reducers/products.js b/examples/shopping-cart/reducers/products.js
index 60bfa729c8..dec38d9cbc 100644
--- a/examples/shopping-cart/reducers/products.js
+++ b/examples/shopping-cart/reducers/products.js
@@ -18,8 +18,9 @@ function byId(state = {}, action) {
return Object.assign({},
state,
action.products.reduce((obj, product) => {
- obj[product.id] = product;
- return obj;
+ const newObj = obj;
+ newObj[product.id] = product;
+ return newObj;
}, {})
);
default: {
diff --git a/examples/todomvc/components/MainSection.js b/examples/todomvc/components/MainSection.js
index 65cbb65a72..c649fddcf3 100644
--- a/examples/todomvc/components/MainSection.js
+++ b/examples/todomvc/components/MainSection.js
@@ -65,9 +65,8 @@ class MainSection extends Component {
const filteredTodos = todos.filter(TODO_FILTERS[filter]);
const completedCount = todos.reduce((count, todo) => (
- todo.completed ? count + 1 : count,
- 0
- ));
+ todo.completed ? count + 1 : count
+ ), 0);
return (
diff --git a/examples/todomvc/test/components/Footer.spec.js b/examples/todomvc/test/components/Footer.spec.js
index 6176d360a7..04cdb3b9a0 100644
--- a/examples/todomvc/test/components/Footer.spec.js
+++ b/examples/todomvc/test/components/Footer.spec.js
@@ -82,7 +82,7 @@ describe('components', () => {
it('shouldnt show clear button when no completed todos', () => {
const { output } = setup({ completedCount: 0 });
const [, , clear] = output.props.children;
- expect(clear).toBe(undefined);
+ expect(clear).toBe(null);
});
it('should render clear button when completed todos', () => {
diff --git a/examples/tree-view/reducers/index.js b/examples/tree-view/reducers/index.js
index 2cc9d9716d..04123547cc 100644
--- a/examples/tree-view/reducers/index.js
+++ b/examples/tree-view/reducers/index.js
@@ -42,7 +42,7 @@ function getAllDescendantIds(state, nodeId) {
function deleteMany(state, ids) {
const newState = Object.assign({}, state);
ids.forEach(id => delete newState[id]);
- return state;
+ return newState;
}
export default function (state = {}, action) {
diff --git a/src/bindActionCreators.js b/src/bindActionCreators.js
index 3b4f4c5abf..8f2d265974 100644
--- a/src/bindActionCreators.js
+++ b/src/bindActionCreators.js
@@ -30,7 +30,8 @@ export default function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error(
- `bindActionCreators expected an object or a function, instead received ${actionCreators === null ? 'null' : typeof actionCreators}. ` +
+ 'bindActionCreators expected an object or a function, ' +
+ `instead received ${actionCreators === null ? 'null' : typeof actionCreators}. ` +
'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
);
}
diff --git a/src/combineReducers.js b/src/combineReducers.js
index 20863a2e46..3e9e07b5f5 100644
--- a/src/combineReducers.js
+++ b/src/combineReducers.js
@@ -26,11 +26,10 @@ function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) {
}
if (!isPlainObject(inputState)) {
+ const argumentType = ({}).toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1];
return (
- `The ${argumentName} has unexpected type of "` +
- ({}).toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] +
- '". Expected argument to be an object with the following ' +
- `keys: "${reducerKeys.join('", "')}"`
+ `The ${argumentName} has unexpected type of "${argumentType}". ` +
+ `Expected argument to be an object with the following keys: "${reducerKeys.join('", "')}"`
);
}
@@ -44,6 +43,7 @@ function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) {
`"${reducerKeys.join('", "')}". Unexpected keys will be ignored.`
);
}
+ return null;
}
function assertReducerSanity(reducers) {
@@ -60,7 +60,8 @@ function assertReducerSanity(reducers) {
);
}
- const type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
+ const randomId = Math.random().toString(36).substring(7).split('').join('.');
+ const type = `@@redux/PROBE_UNKNOWN_ACTION_${randomId}`;
if (typeof reducer(undefined, { type }) === 'undefined') {
throw new Error(
`Reducer "${key}" returned undefined when probed with a random type. ` +
diff --git a/src/createStore.js b/src/createStore.js
index 643ee50354..665c6d70cc 100644
--- a/src/createStore.js
+++ b/src/createStore.js
@@ -36,17 +36,20 @@ export const ActionTypes = {
* and subscribe to changes.
*/
export default function createStore(reducer, initialState, enhancer) {
+ let currentState = initialState;
+ let currentEnhancer = enhancer;
+
if (typeof initialState === 'function' && typeof enhancer === 'undefined') {
- enhancer = initialState;
- initialState = undefined;
+ currentEnhancer = initialState;
+ currentState = undefined;
}
- if (typeof enhancer !== 'undefined') {
- if (typeof enhancer !== 'function') {
+ if (typeof currentEnhancer !== 'undefined') {
+ if (typeof currentEnhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.');
}
- return enhancer(createStore)(reducer, initialState);
+ return currentEnhancer(createStore)(reducer, currentState);
}
if (typeof reducer !== 'function') {
@@ -54,7 +57,6 @@ export default function createStore(reducer, initialState, enhancer) {
}
let currentReducer = reducer;
- let currentState = initialState;
let currentListeners = [];
let nextListeners = currentListeners;
let isDispatching = false;
diff --git a/test/typescript.spec.js b/test/typescript.spec.js
index 33ed9acc5e..6093af173a 100644
--- a/test/typescript.spec.js
+++ b/test/typescript.spec.js
@@ -1,7 +1,6 @@
import * as tt from 'typescript-definition-tester';
-
-describe('TypeScript definitions', () => {
+describe('TypeScript definitions', function compileTS() {
this.timeout(0);
it('should compile against index.d.ts', (done) => {