Skip to content

Instantly share code, notes, and snippets.

@monkindey
Created September 18, 2017 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monkindey/ded86d825e6b699445cc951805a3c541 to your computer and use it in GitHub Desktop.
Save monkindey/ded86d825e6b699445cc951805a3c541 to your computer and use it in GitHub Desktop.
redux saga example
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