Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting HTTP Requests in Redux

Tags:

redux

Many redux examples show making HTTP requests directly in an async action; however this will result in an exterme amount of duplicate code common to all requests, for example:

  • Retrying failed requests based on status code
  • Appending common HTTP Headers to each request.
  • Invoking additional http requests based on response (ie: oauth token refresh)
  • Aborting in-flight requests on route transitions.

My gut feeling is that a middleware could be used to make http requests (in the same vein as redux-api-middleware) which can keep the in-flight requests in the store - however I am also wondering if I'm leaning on bad habbits - is a little duplication a small price to pay for immutability?

like image 540
JonnyReeves Avatar asked Sep 14 '25 15:09

JonnyReeves


2 Answers

Your action creators are just JavaScript functions.

If you have duplication between several functions, you extract the common code into another function. This is no different. Instead of duplicating the code, extract the common code into a function and call it from your action creator.

Finally, this pattern can be abstracted away with a custom middleware. Check out the “real world” example in Redux repo to see how it can be done.

like image 193
Dan Abramov Avatar answered Sep 17 '25 09:09

Dan Abramov


All but the aborting could be accomplished while staying immutable by using a request factory which attaches .then and .catch (or equivalent, depending on promise flavor) to the request before returning it.

like image 28
S McCrohan Avatar answered Sep 17 '25 08:09

S McCrohan