Skip to content

Instantly share code, notes, and snippets.

@sergiodxa
Last active June 27, 2018 20:18
Show Gist options
  • Save sergiodxa/40081389617aa68e22ee38459f08ab93 to your computer and use it in GitHub Desktop.
Save sergiodxa/40081389617aa68e22ee38459f08ab93 to your computer and use it in GitHub Desktop.
Ejemplo de redux-saga y prueba de un método `createSaga` similar a `createReducer` de redux-duck
import {
applyMiddleware,
createStore,
} from 'redux';
import createSagaMiddleware, {
takeEvery,
takeLatest,
} from 'redux-saga';
import { call, put } from 'redux-saga/effects';
// delay as promised (to simulate a async request)
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
// create middleware
const sagaMiddleware = createSagaMiddleware()
// test reducer
function reducer(state = 0, action) {
console.log(action);
switch (action.type) {
case 'INCREASE': {
return state + 1;
}
case 'DECREASE': {
return state - 1;
}
default: {
return state;
}
}
}
// our createSaga function
function createSaga(cases) {
return function* saga() {
yield Object
.keys(cases)
.map(function*(caseName) {
const [
caseHandler,
caseSaga,
] = cases[caseName];
if (caseHandler === 'every') {
yield* takeEvery(caseName, caseSaga);
}
if (caseHandler === 'latest') {
yield* takeLatest(caseName, caseSaga);
}
});
}
}
// our custom saga using createSaga
const saga = createSaga({
['MESSAGE_FETCH_REQUESTED']: [
'latest',
function* fetchMessage(action) {
yield call(delay, 500);
yield put({ type: 'DECREASE' });
},
],
['USER_FETCH_REQUESTED']: [
'every',
function* fetchUser(action) {
yield call(delay, 500);
yield put({ type: 'INCREASE' });
},
],
});
// store instance
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
);
// run our saga
sagaMiddleware.run(saga);
// listen changes in the store
store.subscribe(() => console.log(store.getState()));
// dispatch test actions
store.dispatch({
type: 'USER_FETCH_REQUESTED',
});
store.dispatch({
type: 'USER_FETCH_REQUESTED',
});
store.dispatch({
type: 'USER_FETCH_REQUESTED',
});
store.dispatch({
type: 'MESSAGE_FETCH_REQUESTED',
});
store.dispatch({
type: 'MESSAGE_FETCH_REQUESTED',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment