Reputation: 1681
I am attempting to reduce the amount of code I use for the reducers and actions in a ReactJS-Redux application and I am running into some trouble figuring out why the data loaded in a read action populated BOTH reducer keys in the store.
reducer.js;
export class ReducerClass{
constructor(){
this.initialState = {data:[],record:{},loading:false,editmode:0};
}
reducer = (state = this.initialState,action) =>{
let newState = {...state};
switch(action.type){
case "_READ":
newState.data = action.value;
newState.loading = false;
return(newState);
default:
return(newState);
}
}
}
action.js:
export class ActionClass{
constructor(tablename){
this.tablename = tablename;
}
actionRead = (params) => (dispatch) => {
let query = params ? toQueryString(params) : "";
let url = this.tablename + (query ? "?" + query : "");
dbFetch(url, (data) => dispatch({ type: "_READ", value: data }));
}
mapStateToProps = (state) => {
let dataTable = state[this.tablename];
return { data: dataTable.data, record: dataTable.record, loading: dataTable.loading, editmode: dataTable.editmode };
}
mapDispatchToProps = (dispatch) => {
return {
read: (params) => dispatch(this.actionRead(params))
};
}
}
store.js:
import { ReducerClass } from './reducer.js';
let cusdata = new ReducerClass();
let emldata = new ReducerClass();
let rootReducer = combineReducers({
cusdata: cusdata.reducer,
emldata: cusdata.reducer
});
export const Store = createStore(rootReducer, applyMiddleware(thunk));
Obviously I did not include all the imports as most of them are implicit. Declaring the connectors in (lets say) a grid component:
cusDataGridConnect = new ActionClass("cusdata");
export default connect(cusDataGridConnect.mapStateToProps, cusDataGridConnect.mapDispatchToProps)(CusDataGrid);
And For the other grid component:
const emlDataGridConnect = new ActionClass("emldata")
export default connect(emlDataGridConnect.mapStateToProps, emlDataGridConnect.mapDispatchToProps)(EmlDataGrid);
The problem I am running into is when I perform a read on the cusdata grid, the data poplated in both store keys (populated for cusdata AND emldata). Is there anyone who can help with creating a Reducer and Action type class? Most (if not all) of my operations will do the exact same thing and I am attempting to reduce on code duplication. Thanks for any help.
Upvotes: 0
Views: 229
Reputation: 851
I would say the issue is that both ActionClass instances generate the same type of action (_READ), and both reducers listen to this type of actions. You need to provide an arg to both your action and reducer creators (you already do with your action creator: tablename) that you use to construct action types that are specific.
Upvotes: 1