redux logic organizer
npm install --save react-redux-namespacer
// app/redux/todos.dispatchers.js
import { namespace } from 'react-redux-namespacer';
export default namespace('todos', (dispatcher, action) => {
dispatcher('getTodos', (dispatch) => {
get('/todos').then((response) => {
dispatch(action('getTodosSuccess', response.data));
});
});
});
// app/redux/todos.reducers.js
import { reduce } from 'react-redux-namespacer';
const initialState = {
todos: [];
};
export default reduce('todos', initialState, (reducer) => {
reducer('getTodosSuccess', (state, todos) => {
return { ...state, todos };
});
});
// app/redux/reducer.js
import { combineReducers } from 'redux';
import todos from './todos.reducer';
// ...
export default combineReducers({
todos,
// ...
});
// app/components/Todos.jsx
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import dispatchers from 'app/redux/todos.dispatchers';
function mapStateToProps(state) {
return state.todos;
}
class Todos extends PureComponent {
static propTypes = {
todos: PropTypes.arrayOf(PropTypes.object),
getTodos: PropTypes.func
};
componentDidMount() {
this.props.getTodos();
}
render() {
// ...
}
}
export default connect(mapStateToProps, dispatchers.mapToProps)(Todos);
MIT