redux-thunk Example
Simple timeout example
by Caner Dağlı
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://fb.me/react-with-addons-15.0.1.js"></script>
<script src="https://fb.me/react-dom-15.0.1.js"></script>
<link rel="stylesheet" href="https://my.stackla.com/media/components/stackla-uikit/dist/uikit.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.5.2/redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.5/react-redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-thunk/2.1.0/redux-thunk.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
SCSS
.indicator {
font-size: 36px;
height: 50px;
margin-bottom: 10px;
}
Babel + JSX
const {Provider, connect} = ReactRedux;
const {createStore, applyMiddleware} = Redux;
// Step 1. Add the redux-thunk lib
const thunk = ReduxThunk.default;
//============
// Reducer
//============
const defaultState = {
isLoading: false,
lastTimestamp: null,
count: 0,
};
const reducer = (state = defaultState, action) => {
switch (action.type) {
case 'REQUEST_LOAD':
return {
...state,
isLoading: true,
}
case 'RECEIVE_LOAD':
return {
...state,
...action.payload,
count: state.count + 1,
isLoading: false,
}
default:
return state;
}
};
//============
// Actions
//============
function requestLoad() {
return {
type: 'REQUEST_LOAD',
};
}
function receiveLoad(timestamp) {
return {
type: 'RECEIVE_LOAD',
payload: {
lastTimestamp: timestamp,
}
}
}
// Step 3. Define the Action which returns function
// Note that it's a Side Effect Function
function startLoad() {
return (dispatch, getState) => {
dispatch(requestLoad()); // Sub action for REQUEST_LOAD
loadApi()
.then(timestamp => {
// Sub action for RECEIVE_LOAD
return dispatch(receiveLoad(timestamp))
});
}
}
//============
// APIs
//============
// Step 4. Define the async function which returns promise
function loadApi() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(new Date().getTime());
}, 3000);
});
}
//============
// Components
//============
const mapStateToProps = (state = {}) => {
return {...state};
};
let Container = connect(mapStateToProps)(React.createClass({
render: function () {
const {count, dispatch, isLoading, lastTimestamp} = this.props;
return (
<div>
<div...