Created
September 18, 2017 03:16
-
-
Save monkindey/ded86d825e6b699445cc951805a3c541 to your computer and use it in GitHub Desktop.
redux saga example
This file contains hidden or 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 React, { Component } from 'react'; | |
import ReactDOM from 'react-dom'; | |
import { createStore, applyMiddleware } from 'redux'; | |
import { connect, Provider } from 'react-redux'; | |
import createSagaMiddleware, { delay } from 'redux-saga'; | |
import { put, takeEvery, all } from 'redux-saga/effects'; | |
function* incrementAsync() { | |
yield delay(1000); | |
yield put({ type: 'INCREMENT' }); | |
} | |
function* watchIncrementAsync() { | |
yield takeEvery('INCREMENT_ASYNC', incrementAsync); | |
} | |
function* rootSaga() { | |
yield all([watchIncrementAsync()]); | |
} | |
const sagaMiddleware = createSagaMiddleware(); | |
const store = createStore((state = 0, action) => { | |
switch (action.type) { | |
case 'INCREMENT': | |
return state + 1; | |
default: | |
return state; | |
} | |
}, applyMiddleware(sagaMiddleware)); | |
const action = type => { | |
store.dispatch({ type }); | |
}; | |
sagaMiddleware.run(rootSaga); | |
const Counter = ({ value, onIncrement, onDecrement, onIncrementAsync }) => ( | |
<div> | |
<button onClick={onIncrementAsync}>Increment after 1 second</button>{' '} | |
<button onClick={onIncrement}>Increment</button>{' '} | |
<button onClick={onDecrement}>Decrement</button> | |
<hr /> | |
<div>Clicked: {value} times</div> | |
</div> | |
); | |
class Saga extends Component { | |
render() { | |
return ( | |
<div> | |
Saga | |
<Counter | |
value={store.getState()} | |
onIncrement={() => action('INCREMENT')} | |
onDecrement={() => action('DECREMENT')} | |
onIncrementAsync={() => action('INCREMENT_ASYNC')} | |
/> | |
</div> | |
); | |
} | |
} | |
const render = () => ReactDOM.render(<Saga />, document.getElementById('app')); | |
// setState | |
store.subscribe(render); | |
render(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment