I have a functioning redux saga, but I can't stop thinking about how ugly it looks. What I'm trying to do is admittedly a little contrived to simulate async without needing it, but I want to delay one second and then call another function - similar to the tutorial. The difference from the tutorial (which is a simple incrementer) is that I actually need to pass along information. Here is how I'm doing it:
import { delay } from 'redux-saga';
import { put, call, takeEvery, all } from 'redux-saga/effects';
// Our worker Saga: will perform the add employee task
export function* addEmployeeAsync(action) {
yield call(delay, 1000);
console.log(action); // logs undefined on initial app load
const payload = action && action.payload;
yield put({ type: 'ADD_EMPLOYEE', payload });
}
// Our watcher Saga: spawn a new addEmployeeAsync task on each ADD_EMPLOYEE_ASYNC
export function* watchAddEmployeeAsync() {
yield takeEvery('ADD_EMPLOYEE_ASYNC', addEmployeeAsync);
}
export default function* rootSaga() {
yield all([
addEmployeeAsync(),
watchAddEmployeeAsync(),
]);
}
The function is also being called on page load with a payload of undefined
, which may indicate a larger problem I am missing.
The complete code base is here: https://github.com/LukeSchlangen/react-salary-calculator/tree/9ce96409080a3a3f702465791cd28c4c83cadc6f
To reiterate, this code is working, but I can't help but think that there must be a cleaner way to do this.
App.saga.js
where I gather all sagas and have something like yourrootSaga
and then on every module I have a saga file that holds something similar to what you have with thetakeEvery
and everything else. Good job! – Characharabanc