简体   繁体   English

React Redux - 删除对象的数据获取模式

[英]React Redux - data fetching pattern with deletion of objects

I have a react app that displays a list of data and a detail view when clicking on an entry.我有一个反应应用程序,它在单击条目时显示数据列表和详细视图。 I also have a data fetcher that fetches data from my backend every 5 seconds.我还有一个数据获取器,它每 5 秒从我的后端获取数据。

In my detail view I have a delete button that will delete the object on the backend and then returns to the overview page.在我的详细视图中,我有一个删除按钮,它将删除后端的 object,然后返回到概览页面。 After the delete I want to have an instant refresh on the list of objects, so I call the fetching manually.删除后我想对对象列表进行即时刷新,所以我手动调用获取。

So this sometimes gets to a race condition where the automatic data fetching is already in process, the manual starts and finishes first (since the automatic one fetches more data), updates the list so that the deleted one is not shown anymore but then the automatic fetching overwrites this with the old data.所以这有时会进入一个竞争条件,其中自动数据获取已经在进行中,手动开始并首先完成(因为自动获取更多数据),更新列表,以便不再显示已删除的列表,然后自动fetching 用旧数据覆盖它。

How is this commonly solved?这通常是如何解决的?

As I understand your scenario, I think you want to cancel the ongoing server call if a subsequent request is made.据我了解您的情况,我认为如果发出后续请求,您想取消正在进行的服务器调用。 Tod o that you can use axios.CancelToken Tod o 你可以使用axios.CancelToken

For example,例如,

var axios = require("axios")

var CancelToken = axios.CancelToken;
var call1 = CancelToken.source();
var call2 = CancelToken.source();

axios.get('http://your/api/call', {
  cancelToken: call1.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Ongoing server call is cancelled', thrown.message);
  } else {
    // handle error
  }
});

setTimeout(function() {
    // Cancel ongoing server call
    call1.cancel('Stopping current server call');

    // Server call on delete
    axios.get('https://your/api/call', {
      cancelToken: call2.token
    }).then(function(response) {
        console.log('Success', response.status);
    });
}, 1000) 

Hope this will help you.希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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