1

In a simple TO-DO app it's straightforward to manage your app state by putting all reducers in a folder and combine them and then import your reducers into the main JS file and create your store.

import {createStore} from 'redux';

import reducers from './reducers';

const store = createStore(reducers);

But in a case where you have multiple routes and you want to better organize you directory structure by keeping each route with its own reducers folder.

Something like this:

routes
  |-- contact
  |   |-- components
  |   |-- actions
  |   |-- reducers
  |
  |-- products
      |-- components
      |-- actions
      |-- reducers

My question is how should I handle my app state in such case? And how my main.js file would look like?

bigfanjs
  • 754
  • 3
  • 7
  • 17

1 Answers1

2

Import you reducers and use redux's combineReducers:

import {createStore, combineReducers } from 'redux';
import contact from 'routes/contact/reducers';
import products from 'routes/products/reducers';

const rootReducer = combineReducers({ contact, products });

const store = createStore(rootReducer);

For better organization, create a rootReducer.js file and combine all your reducers there. Then Import the rootReducer on you createStore file.

nirsky
  • 2,955
  • 3
  • 22
  • 35
  • I've actually already tried that. I thought there has to be a way to dynamically add new reducers at run-time but it seems like the only way to do it is by declaring all your reducers before running your app unless you want to asynchronously replace reducers for code-splitting. And that how I think Redux was designed to be. Thank you! – bigfanjs Apr 30 '17 at 15:44
  • It _is_ possible - see http://stackoverflow.com/questions/32968016/how-to-dynamically-load-reducers-for-code-splitting-in-a-redux-application and https://medium.com/@jimmy_shen/inject-reducer-arbitrarily-rather-than-top-level-for-redux-store-to-replace-reducer-fdc1060a6a7 for examples of adding reducers at runtime. – markerikson May 01 '17 at 15:33