maletor
maletor

Reputation: 7122

Cancel HTTP fetch request using React hooks

Does this look like a reasonable, if verbose, way to make sure that each click does not stack requests to saveOperation?

I'm using RxJS and storing the instance of the subscription in a mutable ref so it persists between renders. Then, if one exists, I cancel it before starting a new one.

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} />

Upvotes: 0

Views: 465

Answers (1)

Jonathan Stellwag
Jonathan Stellwag

Reputation: 4267

A more reactive way of solving your issue would be the to always have your subscription open and let your pipe control the data flow. One way could be the usage of switchMap.

One asynchronous value that changes over time is your text input. That could be the outer observable that unsubscribes your inner http request and starts a new one:

// 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);

Running stackblitz

Upvotes: 2

Related Questions