README
vb-component-template
This repository, built from vb-component-template
, provides an example on how to use Redux and Redux Saga together with common components from vb-js-commons
.
Redux
Example Reducer
The following is an example, standard Redux reducer:
const exampleReducer = (state = { count: 0 }, action) => {
switch (action.type) {
case "HELLO":
return Object.assign({}, state, {
count: state.count + 1
});
default:
return state;
}
};
const store = createStore({
additionalReducers: {
hello: exampleReducer
}
});
Example saga
The following example saga dispatches an additional SAGA_ACTION, with it's payload read from the global Redux state, 1000ms after every HELLO action.
const exampleSaga = function*() {
yield takeEvery("HELLO", function*() {
console.log("exampleSaga acting on HELLO");
yield delay(1000);
const state = yield select();
yield put({ type: "SAGA_ACTION", payload: { count: state.hello.count } });
});
};
const store = createStore({
additionalReducers: {
hello: exampleReducer
},
additionalSagas: [exampleSaga]
});
Connecting to Redux
Here we create a Redux container:
const ConnectedCommonComponent = connect(
state => ({ count: state.hello.count }),
dispatch => ({
increaseCount: () => dispatch({ type: "HELLO", payload: {} })
})
)(CommonComponent);
And then use it within a Provider:
render() {
return (
<Provider store={store}>
<ConnectedCommonComponent />
</Provider>
);
}