Reputation: 69
Having a problem with redux-saga
here. I am calling toggleSidebar()
to open / close the sidebar. That works, however, the saga is ignored. I log to the console using console.log
in my reducer
and saga
, but only the reducer
logs to the console.
The sidebar opens / closes, but why is the saga being ignored?
/sagas/templateSaga.js - Does not log to the console
import { FETCH_DEFAULT_TEMPLATE, RECEIVE_DEFAULT_TEMPLATE } from '../actions'
function* toggleSidebar(action) {
console.log("Called toggleSidebar in Saga")
yield put({type: 'TOGGLE_SIDEBAR', data: action.payload});
}
export default function* templateSaga() {
yield takeLatest("TOGGLE_SIDEBAR", toggleSidebar);
}
/reducers/templateReducer.js - Logs to the console
export default (state = initialState, {type, data = ""}) => {
switch (type) {
case TOGGLE_SIDEBAR: {
console.log("Called toggleSidebar in reducer");
return {...state, collapsed: data}
}
default: {
return {
...state
}
}
}
}
/actions/index.js
export const TOGGLE_SIDEBAR = 'TOGGLE_SIDEBAR'
export const toggleSidebar = data => ({type: TOGGLE_SIDEBAR, data})
/reducers/index.js ( rootReducer )
import templateReducer from './templateReducer'
export default combineReducers({
templateReducer
})
/sagas/index.js ( rootSaga )
import templateSaga from './templateSaga'
export default function* rootSaga() {
yield all([
...templateSaga
])
}
My store is configured like that:
import createSagaMiddleware from 'redux-saga'
import rootReducer from '../modules/reducers'
import rootSaga from '../modules/sagas'
const sagaMiddleware = createSagaMiddleware(rootSaga);
const middleware = [
sagaMiddleware,
routerMiddleware(history)
]
export const store = createStore(
rootReducer,
applyMiddleware(...middleware)
)
sagaMiddleware.run(rootSaga)
And finally, in my App I am using:
const mapStateToProps = state => ({
template: state.templateReducer
})
const mapDispatchToProps = dispatch =>
bindActionCreators({ toggleSidebar }, dispatch)
export default connect(mapStateToProps, mapDispatchToProps)(App);
Upvotes: 1
Views: 402
Reputation: 695
The error probably in /sagas/index.js
( rootSaga )
Try to change ...templateSaga
to fork(templateSaga)
like so:
import { fork } from 'redux-saga/effects'
import { templateSaga } from './templateSaga'
export default function* rootSaga() {
yield all([
fork(templateSaga)
])
}
And change export default function* templateSaga
to
export function* templateSaga() {
yield takeLatest("TOGGLE_SIDEBAR", toggleSidebar);
}
Also, you have some kind of a loop in /sagas/templateSaga.js
where you take 'TOGGLE_SIDEBAR'
and dispatch the same type right away
Upvotes: 1