简体   繁体   中英

Redux async API calls - most up to date state

I am currently working for an Austrian company, we are developing a document management system for Windows. In early 2017 we started creating a web application using Angular. However we started to get some problems with the state of the app.

We are thinking of using Redux as a state-manager, we have one concern though.

Let's say we have a table with 2 documents

|--------------------------------|
| Document1.pdf                  |
|--------------------------------|
| Document2.pdf                  |
|--------------------------------|

We also have a preview of the selected document.

Say we click on Doc 1 (it takes the server 5 seconds to load the document). 1 second after clicking on Doc1 we click on Doc2 (it takes the server only 1 second to load the document). A second later Doc2 shows up in the preview, however 4 seconds the later Doc1 gets loaded and shows up in the preview. Although we currently have Doc2 selected.

When using Redux do we have to manually check for the "correct" document or does the framework everything for us and we just have to implement the server calls without thinking of app's state?

Redux is a predictable state container for JavaScript apps.

That's how the Redux docs start. Redux is not managing your state. It only keeps it and provides a deterministic-ish mutations. It teaches some very good practices and it is in fact a really smart piece of software. However, it can't solve your problem without a little help from you. Redux is not about managing state. It is about managing processes that lead to managing your state.

I would solve your problem by using a marker of what the user clicked lately. For example:

action                 | state
--------------------------------
clicking on Doc1       | state = { itemSelected: 'Doc1', data: null }
clicking on Doc2       | state = { itemSelected: 'Doc2', data: null }

Then later when a response comes we need a payload in the form of

{ itemToLoad: 'Doc1', data: {...} }

And the rest is easy, we just check if the itemToLoad is equal to itemSelected . If yes then we update the data.

if (payload.itemToLoad === currentState.itemSelected) {
  return {
    itemSelected: currentState.itemSelected,
    data: payload.data
  }
} else {
  // if not equal we just ignore it and return the current state
  return currentState;
}

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