Redux Patterns and Anti-Patterns
Chet Corcos
42715

I really liked this article. There were parts of it that made me feel good because I was already doing what you said and there parts that gave me ideas about other cool things I could implement.

One of the things that I am already doing is your concept of abstracting away the calls to the server behind an api module. I am currently building a greenfield front end for a legacy backend using Redux and with such a Herculean task ahead of me it’s great to be able to defer some decisions, like which HTTP module I go for, until later by making these api modules. As long as I can make whichever HTTP module I got for return a promise I’m sorted.

The problem that I’ve found with doing this api module pattern is; how in the heck do you switch it out based on environment?! For example in my tests for my action creators I want it to load up a little mocked promised thing that I’ve made so that the tests run really quickly but then when I serve it up and run the application in development mode I want to load in a module that returns mocked up server responses, and in release mode obviously I want the real server calls to be made.

Currently I’ve addressed this problem by adding a variable to into my webpack config which holds a value for which environment the build is running in. I can then use this to require in orderApiModule.dev.js or orderApiModule.test.js etc. as I see fit. As it stands I’v got this require running in an IIFE that requires the appropriate module and then loads the result into a variable in the scope of my action creators module ready for use.

There in lies the rub, I can’t shake the feeling that this environment switching logic doesn’t belong in the action creators themselves and that perhaps it should be getting injected instead. But then the question needs to be asked, injected from where? It’s hard to know what the right thing to do is in this situation.

Am I just being paranoid or do you agree? I was wondering if you might share with us how you handle the mocking of your api modules either in my comment here or as another blog post?

Once again, great article I really enjoyed reading it, thanks.

Zac

Show your support

Clapping shows how much you appreciated Zac Braddy’s story.