简体   繁体   中英

What's the best pattern for dealing with asynchronous requests in React?

React is all about pure state, and I have a status variable in my App component's state that keeps track of what the app is currently doing. To simplify things, let's say there are three states: Waiting for Input , Fetching URL , and Error .

When the user submits a URL, the state changes to Fetching URL and a $.get() request is fired to fetch data from it. Once the request succeeds or fails, the app state changes to Waiting for Input or Error , respectively.

My problem is that when the user submits another URL in the Fetching URL state, it is reasonable to cancel the previous URL request and reenter the Fetching URL state with the new URL. What is the most elegant pattern to handle this in React? Currently, my solution is checking in the $.get() request's success() and fail() callbacks to make sure that the current URL didn't change before updating the state. However, this solution does not scale as I would have to include the check in every callback of every asynchronous request I make.

If you only want to move into 'Waiting' state when all fetches are complete you'll need to track them somehow. This isnt really a React problem.

Simplest solution would just be to store the open fetch requests in an array somewhere and remove them when they complete. When you remove them check if the list is empty and update your state accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM