How to avoid race conditions when fetching data with Redux?

后端 未结 2 1897
萌比男神i
萌比男神i 2021-01-30 05:11

We have an action that fetches an object async, let\'s call it getPostDetails, that takes a parameter of which post to fetch by an id. The user is presented with a

2条回答
  •  一个人的身影
    2021-01-30 05:54

    Dan's solution is probably a better one, but an alternative solution is to abort the first request when the second one begins.

    You can do this by splitting your action creator into an async one which can read from the store and dispatch other actions, which redux-thunk allows you to do.

    The first thing your async action creator should do is check the store for an existing promise, and abort it if there is one. If not, it can make the request, and dispatch a 'request begins' action, which contains the promise object, which is stored for next time.

    That way, only the most recently created promise will resolve. When one does, you can dispatch a success action with the received data. You can also dispatch an error action if the promise is rejected for some reason.

提交回复
热议问题