React Base Fiddle (JSX)
async-await
by jeffbski
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/axios/dist/axios.min.js"></script>
<script src="https://npmcdn.com/redux@^3.5.2/dist/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser-polyfill.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/redux-logic.min.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div class="desc">
<h1>single-file-redux-async-await</h1>
Single file example of redux-logic and async functions (async/await) used
with redux only. Output is being appended to the container div. See also
the console.log for actions being fired in between state changes.
<div> </div>
</div>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
JavaScript 1.7
const { createStore, applyMiddleware } = Redux;
const { createLogic, createLogicMiddleware } = ReduxLogic;
const initialState = {
list: [],
fetchStatus: ''
};
const USERS_FETCH = 'USERS_FETCH';
const USERS_FETCH_CANCEL = 'USERS_FETCH_CANCEL';
const USERS_FETCH_FULFILLED = 'USERS_FETCH_FULFILLED';
const USERS_FETCH_REJECTED = 'USERS_FETCH_REJECTED';
function usersFetch() {
console.log('action USERS_FETCH dispatched');
return { type: USERS_FETCH };
}
function usersFetchCancel() {
console.log('action USERS_FETCH_CANCEL dispatched');
return { type: USERS_FETCH_CANCEL };
}
function usersFetchFulfilled(users) {
return { type: USERS_FETCH_FULFILLED, payload: users };
}
function usersFetchRejected(err) {
return { type: USERS_FETCH_REJECTED, payload: err, errror: true };
}
const delay = 2; // 2s delay for interactive use of cancel/take latest
const usersFetchLogic = createLogic({
type: USERS_FETCH,
cancelType: USERS_FETCH_CANCEL,
latest: true, // take latest only
// use axios injected as httpClient from configureStore logic deps
// we also have access to getState and action in the first argument
// but they were not needed for this particular code
async process({ httpClient }, dispatch, done) {
try {
// the delay query param adds arbitrary delay to the response
const users =
await httpClient.get(`https://reqres.in/api/users?delay=${delay}`)
.then(resp => resp.data.data); // use data property of payload
dispatch(usersFetchFulfilled(users));
} catch(err) {
console.error(err); // log since could be render err
dispatch(usersFetchRejected(err));
}
done();
}
});
const deps = { // injected dependencies for logic
httpClient: axios
};
const arrLogic = [usersFetchLogic];
const logicMiddleware = createLogicMiddleware(arrLogic, deps);
const store = createStore(reducer, initialState,
applyMiddleware(logicMiddleware));
const...