使用React钩子取消HTTP提取请求

时间:2020-03-16 19:16:58

标签: reactjs rxjs

这看起来是否合理(如果冗长),可以确保每次点击都不会堆积对saveOperation的请求?

我正在使用RxJS并将订阅实例存储在可变引用中,因此它在渲染之间持久存在。然后,如果存在的话,我先取消它,然后再开始新的一个。

const saveSubscription = useRef<Subscription>(); // RxJS Subscription (cancellable fetch)

const handleChange = () => {
  saveSubscription.current?.unsubscribe();
  saveSubscription.current = saveOperation({ ...data }).subscribe();
}

...

<input type="text" onClick={() => handleChange()} ref={fileInput} />

1 个答案:

答案 0 :(得分:1)

解决问题的一种更被动的方法是始终打开订阅并让管道控制数据流。一种方法可能是使用switchMap

一个随时间变化的异步值是您的文本输入。那可能是外部可观察到的,它取消了您内部的http请求的订阅并开始了一个新请求:

// Outer text observable that changes via your input
const text$ = new Subject();

// A fake http function to show async http responses
const fakeHttp$ = (text: string) => of('Http answer: ' + text).pipe(delay(1000));

// The http response that can be subscribed to, cancels the fakeHttp request if a new text$ emits within the old open request
const source$ = text$.pipe(
  switchMap(fakeHttp$)
);

// Your handle change function that can be called in the JSX Input
handleChange = (text: string) => text$.next(text);

运行stackblitz