Last active
October 10, 2015 04:05
-
-
Save namelos/af1790be50a3a1f978bc to your computer and use it in GitHub Desktop.
minimalist async action example for redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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