Hacker News new | past | comments | ask | show | jobs | submit login

I find this string pattern terrible as well. As the application grows, there are lots of reducers with lots of strings, and it gets really confusing. It feels like this is inherited from Flux (https://facebook.github.io/flux/), Facebook's initial solution to handling state.

On the other hand, you have all the state logic on reducers... If actions were to dispatch state-modifying functions, it wouldn't take long for the code to become really confusing.




I'm not sure why everyone is getting hung up on the fact that this is implemented with strings and a switch statement. Who cares? Use constants. If JS had enums we would use them, but it doesn't.

The point is that there are a finite, well-enumerated set of possible state changes, which are all localized in one place: the reducer. Whether you call them "DO_THING" vs. constants.actions.DO_THING (which could be an integer or whatever you want) or whether you use a switch statement vs. if block vs. dictionary lookup is entirely up to you.


I'm not sure why but a lot of developers think or are taught that switch statements are old fashioned or even bad.


Probably because programmers new to OO tend to use them when inheritance/interfaces would be cleaner (case cat, case dog, etc.)


Facebook still uses Flux, and it was created specifically for large applications. The thing which is missing from this example is some kind of namespacing. In a large application, you should be naming your action types in such a way that it is not confusing which application feature they relate to, eg. if you had domain logic relating to something called 'UserProfile', you might have an action like `USER_PROFILES/UPDATE_PHOTO`. Combined with sensible project layout and file naming (eg. by domain) this should make it easy to track down code relating to a particular action. It also makes for excellent 'greppability'.

If you're using a JS typechecker like Flow (and IMO if you're building a large app, you should) you can even make use of disjoint unions to type your Flux action objects: https://flowtype.org/blog/2015/07/03/Disjoint-Unions.html


It's not so bad if you keep your exported consts in a file with JsDoc comments.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: