Skip to content

Instantly share code, notes, and snippets.

@ushiboy
Last active July 5, 2016 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ushiboy/b2ec37e1a1daeceeadf9d4c89753eef2 to your computer and use it in GitHub Desktop.
Save ushiboy/b2ec37e1a1daeceeadf9d4c89753eef2 to your computer and use it in GitHub Desktop.
Redux Progress Case
import React from 'react';
import { render } from 'react-dom';
import { createStore, bindActionCreators, applyMiddleware } from 'redux';
import { Provider, connect } from 'react-redux';
import thunk from 'redux-thunk';
const START = Symbol();
const UPDATE_PROGRESS = Symbol();
const COMPLETE = Symbol();
function progress(state={rate:0, completed: false, running: false }, action) {
const { type, payload } = action;
switch (type) {
case START:
return Object.assign({}, state, {
completed: false,
running: true
});
case UPDATE_PROGRESS:
return Object.assign({}, state, {
rate: payload.rate
});
case COMPLETE:
return Object.assign({}, state, {
completed: true,
running: false
});
default:
return state;
}
}
const store = createStore(progress, undefined, applyMiddleware(thunk));
function heavyProcess(onProgress) {
return [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100].map(n => {
return () => {
return new Promise(resolve => {
setTimeout(() => {
onProgress(n);
resolve();
}, 250);
});
};
}).reduce((a, b) => {
return a.then(b);
}, Promise.resolve());
}
// Actions
function run() {
return dispatch => {
dispatch({
type: START
});
heavyProcess(rate => {
dispatch({
type: UPDATE_PROGRESS,
payload: {
rate
}
});
}).then(r => {
dispatch({
type: COMPLETE
});
});
};
}
// View
function App(props) {
const { rate, completed, running, run } = props;
const message = completed ? 'done!' : '';
return (
<div>
<h1>Progress</h1>
<p>{rate} {message}</p>
<button onClick={run} disabled={running}>Run</button>
</div>
);
}
const ConnectedApp = connect(
state => state,
dispatch => bindActionCreators({ run }, dispatch)
)(App);
render(
<Provider store={store}>
<ConnectedApp />
</Provider>,
document.getElementById('app')
);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Progress</title>
</head>
<body>
<div id="app"></div>
<script src="bundle.js"></script>
</body>
</html>
{
"name": "redux-progress",
"version": "0.1.0",
"description": "",
"main": "app.js",
"scripts": {
"build": "browserify app.js -t [ babelify --presets [ es2015 react ] ] -o bundle.js"
},
"author": "",
"license": "MIT",
"dependencies": {
"react": "^15.1.0",
"react-dom": "^15.1.0",
"react-redux": "^4.4.5",
"redux": "^3.5.2",
"redux-thunk": "^2.1.0"
},
"devDependencies": {
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.5.0",
"babelify": "^7.3.0",
"browserify": "^13.0.1",
"eslint": "^3.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment