0

As discussed here, it seems that React reducers must be pure functions and never generate side-effects (no API calls changing anything). Is it safe to throw an Error in a reducer in case of an invalid input)? (Isn't that considered a side-effect?)

Shayan
  • 2,758
  • 7
  • 36
  • 55

2 Answers2

1

It is not safe. You should always do your checking before.

For example in a middleware. Stop the action from reaching the reducer and throwing an error from there.

CevaComic
  • 2,056
  • 2
  • 6
  • 12
  • Could you explain why? It seems to me that when an Error is thrown the changes made inside the reducer are not used for changing the state and thus no problem can occur. – Shayan Jun 15 '20 at 12:31
  • Because if you throw an error in a reducer you will stop the reducer from returning the state, in this case you will cause a crash of your app and in some cases your store won't work at all , it will freeze (no further actions will be taken by reducers). – CevaComic Jun 15 '20 at 12:34
  • Are you sure about that? If it is as you said, if an error is made in some rare case by mistake, it may ruin your whole application without a possibility of repair. It seems more natural to me that if reducer could not run for whatever reason, no state change occurs. – Shayan Jun 16 '20 at 06:19
  • Could you give a reference for that? – Shayan Jun 16 '20 at 06:20
  • [Check this link](https://www.valentinog.com/blog/redux/) and read about reducers, this guy knows better than me, this is where I first studied redux. – CevaComic Jun 16 '20 at 16:16
1

Is it safe to throw an Error in the reducer?

The answer to this question states that if an Error is thrown, redux will do nothing and the application will be left with the previous state.

So, assuming the implementation has not changed, it is probably safe (no resulting damage) as long as you haven't mutated the previous state, which a pure function should never do.

Is it a good idea to rely on throwing in a reducer?

No. As you stated, throwing is a side effect and there probably won't be possible to write error handling code for it anyway.

The best approach (see linked question) is probably to catch the error inside the reducer and update the state to indicate it properly.

Blanc
  • 175
  • 12