Jalil
Jalil

Reputation: 3178

Conditional Redux reducer usage

I'm working on an application where I want to manage different business subdomains.

The domain type is in my store.

I have created specific components, loaded depending on my store state. For exemple :

let component;
 switch (this.props.somestate.somevar)
 {
   case 'business1':
   default:
     component = require('path/to/business1/B1Component').default;
     break;
   case 'business2' :
     component = require('path/to/business2/B2Component').default;
     break;
 }
 return <component {...this.props} />

But I would also like to use specific reducers for those subdomains, loaded by store.replaceReducer() only if needed.

I found a way to do it based on route, like this for example : How to dynamically load reducers for code splitting in a Redux application?

Like the example above, I would like to keep all common reducers, but adding some business-specific reducers based on what API returns.

But in my case, the route does not say which subdomain is concerned, I get this information by API call and it's stored in Redux store.

Should I write a middleware to intercept this information and call replaceReducer on my store ? Should I do it directly from a Higher-order component ? Is what I want to do a bad practice / anti-pattern ?

I'm not sure what's the best pattern/practice here ...

Upvotes: 3

Views: 1420

Answers (1)

Dan Abramov
Dan Abramov

Reputation: 268313

Since what you are doing is a little bit unusual there are no best practices or anti-patterns here. I would say that this approach should work just fine for you as well, and it doesn’t really matter where you call replaceAsyncReducer (or whatever you decide to call it). Route handlers are just one possible example, but it is fine to do that from componentWillMount of the relevant component, or wherever you make the API call, or even from a dedicated middleware, as long as it’s easy to trace why this happens. Since it’s a little unusual I would suggest to have as little indirection as possible so start with the simplest solution (in your case it sound like the API call is the best place to put it).

Upvotes: 2

Related Questions