0

I have a react-redux application which:

  1. Loads N records from the database depending on a "limit" query parameter (by default 20 records) on first application load (initialization)
  2. Every 10 seconds app requests same (or newer) records from the database to update data in real time
  3. If a user changes filters - app requests new records from the database according to the filter and re-renders app (+ changes interval to load data according to the filters)
  4. If users scrolls down, the app automatically loads more records.

The problem is that if a user for and instance tries to filter something out and at this same time interval is loading more data, 2 requests can clash and overwrite each other. How in react-redux app I can be sure in a request sequence. Maybe there is a common approach on how to properly queue requests?

Thanks in advance!

Andy Marrel
  • 103
  • 1
  • 6
  • You could handle your use case easily with redux-observables, see for example this SO question: https://stackoverflow.com/questions/50160430/cancel-previous-requests-and-only-fire-the-latest-request-with-redux-observable – Harald Gliebe Mar 30 '19 at 12:11

1 Answers1

0

I am not sure what you mean by 'clash'. My understanding is that the following will happen:

  • Assuming that both requests are successful, then data is retrieved for each of them, the redux state will be updated twice, and the component which renders the updated state will render twice (and the time passed between the two renders might be very short, which might not be very pleasant to the user)

If you want only one of these two requests to refresh the component, then a possible solution may be the following:

  • Each request starts, before retrieval of data from the database, by creating a 'RETRIEVAL_START' action. 'RETRIEVAL_START' will set a redux state variable 'retrievalInProgress'

  • If you want, in such a case, to get results only from the 1st of the two requests, you can check, before calling the action creator from the component, if 'retrievalInProgress' is on. If it is, don't call the action creator (in other words, do not request data when a request is in progress). 'retrievalInProgress' will be cleared upon successful or failed retrieval of data.

  • If you want to get results only from the 2nd of the two requests, then make 'retrievalInProgress' a counter, instead of a boolean. In the 'retrievalSuccess' action of the reducer, if this counter is higher than 1, it means that a new request already started. In this case, do not update the state, but decrement the counter.

I hope that this makes sense. I cannot be 100% sure that this works before I test it, which I am not going to do :), but this is the approach I would take.

Yossi
  • 5,577
  • 7
  • 41
  • 76