Skip to content

Instantly share code, notes, and snippets.

@namelos
Last active October 10, 2015 04:05
Show Gist options
  • Save namelos/af1790be50a3a1f978bc to your computer and use it in GitHub Desktop.
Save namelos/af1790be50a3a1f978bc to your computer and use it in GitHub Desktop.
minimalist async action example for redux
import request from 'superagent';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import { createStore, applyMiddleware } from 'redux';
const req = () => ({ type: 'REQ' });
const rec = data => ({ type: 'REC', data });
const fetch = () => dispatch => {
dispatch(req());
return request.get('http://localhost:3000/api')
.end((err, res) => dispatch(rec(JSON.parse(res.text).text)));
};
const fetcher = (state = {}, action) => {
switch (action.type) {
case 'REQ':
return Object.assign({}, state, {
isFetching: true
});
case 'REC':
return Object.assign({}, state, {
isFetching: false,
data: action.data
})
default:
return state;
}
};
const logger = createLogger();
const createStoreWithMiddleware = applyMiddleware(thunk, logger)(createStore);
const store = createStoreWithMiddleware(fetcher);
store.dispatch(fetch());
const path = require('path');
const express = require('express');
const app = express();
app.get('/api', (req, res) =>
res.send(JSON.stringify({ text: 'Hello' });
// please put a simple index.html with bundle.js packed from the script above.
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3000, () => 'listening at 3000...')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment