Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I store promises in Redux?

I'm using Redux and React in an online food-ordering app.

When the user removes an item from their basket, I need to fire off an XHR request to the server to compute the new total price for the basket. When this XHR completes, I update the redux store and render the new price. I'm using Redux thunk to manage this async operation.

There is a problem is a user removes two items from the basket in quick succession. The user removes the first item, and I fire off an XHR to get the new price. Then the user clicks a button to remove a second item, and a second XHR is fired off.

The UI will be in an incorrect state if the second XHR completes before the first - the price of the basket with only the first item removed will be shown.

To work around this, I want to cancel the first (in-flight) XHR when the user clicks the button to remove the second item. To cancel the first XHR I need to keep track of the promise object (I'm using axios to manage XHR).

It makes sense to me to store the in-flight XHR in the redux store. Is it bad practice to store promises in Redux like this? It seems to be frowned upon - Redux should really just be storing plain data.

like image 864
Marc O'Morain Avatar asked Feb 24 '17 17:02

Marc O'Morain


1 Answers

This is covered in the Redux FAQ, at http://redux.js.org/docs/faq/OrganizingState.html#organizing-state-non-serializable :

It is highly recommended that you only put plain serializable objects, arrays, and primitives into your store. It's technically possible to insert non-serializable items into the store, but doing so can break the ability to persist and rehydrate the contents of a store, as well as interfere with time-travel debugging.

Generally, any async behavior like this is handled externally to the Redux store, via promises or middleware like redux-thunk, redux-saga, or redux-observable. For some comparisons between these approaches, see the recent articles Redux 4 Ways and 3 Common Approaches to Side-Effects in Redux.

like image 164
markerikson Avatar answered Oct 20 '22 15:10

markerikson