I am a little confused on how to dynamically create reducers in Redux. I have found a few Stackoverflow questions on this topic but they seem to cover different use cases and I am regretfully confused with the suggested solutions.
Here is my use case. I have a pallet of React DnD components available to the user. When the user drags a component onto the specified drop area, I am building out a simple div for a visual representation and for reference. The component will contain an ID as props and when it’s dropped I’m adding the ID to the div and I want to create a new reducer for the dropped component with the components ID as the attribute on the global state object.
This ID will map the attribute on the global state object to the div on the ui.
I can somewhat follow the solution provider here, but I get lost when I come to the routes.js section: How to dynamically load reducers for code splitting in a Redux application?
This is how I have always structured my reducers. Can I somehow generate new reducers dynamically using this structure?
reducers/index.js
import { combineReducers } from 'redux';
import usersReducer from './users_reducer.js';
const rootReducer = combineReducers({
users: usersReducer
});
export default rootReducer;
reducers/users_reducer.js
import {
FETCH_USERS
} from '../actions/types';
const INITIAL_STATE = { all: [], user: {} };
export default function(state = { INITIAL_STATE }, action) {
switch (action.type) {
case FETCH_USERS:
return {...state, all: action.payload };
default:
return state;
}
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, browserHistory } from 'react-router';
import reducers from './reducers';
import routes from './routes.js';
import promise from 'redux-promise';
import reduxThunk from 'redux-thunk';
import logger from 'redux-logger';
const createStoreWithMiddleware = applyMiddleware(
reduxThunk,
logger()
)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes}/>
</Provider>
, document.querySelector('#app')
);
Any advice on how I should go about structuring this flow would be greatly appreciated!