question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

API Request - cancelation of asynchronous selector

See original GitHub issue

Thanks for sharing Recoil with the React community, it looks great. Having worked previously with libraries like RxJs one of the first things I look for with async state is the ability to cancel tasks. From what I can tell, and please do correct me if I am wrong, is that this is not currently supported. Raising a ticket to discuss if it could be part of a future version of Recoil 😀

Use case: An asynchronous selector makes a network request using the Fetch API. When a selector’s dependancies changes and a new request is made then the previous request could ideally be aborted to avoid unnecessary work.

const currentUserInfo = selector({
  key: 'CurrentUserInfo',
  get: async ({get}) => {
    // If the 'currentUserIDState' atom changes this request is not canceled
    const req = await fetch(`/user?id=${get(currentUserIDState)}`);
    return await req.json();
  },
});

Related APIs: The function passed to React.useEffect may return a clean-up function. Note: Recoil can’t follow this exact same pattern right now because the current API expects a promise to be returned.

Possible approach:

Pass a cleanup function to the selector’s get. Passing a function to cleanup would register it ready to be called by recoil when the selector is invalidated.

const currentUserInfo = selector({
  key: 'CurrentUserInfo',
  get: async ({get, cleanup}) => {
    const controller = new AbortController();
    const signal = controller.signal;
    cleanup(() => controller.abort());

    const req = await fetch(`/user?id=${get(currentUserIDState)}`, {signal});
    return await req.json();
  },
});

Alternatives:

Instead of having built-in support for cancelation it might be possible to implement cancelation in user space. This would stop the get being a pure function so is possibly breaking a “rule of recoil” and therefore not safe.

EDIT: This approach is not safe https://github.com/facebookexperimental/Recoil/issues/51#issuecomment-629747819 🔥

const currentUserInfo = (() => {
    let cleanup = null;
    return selector({
      key: 'CurrentUserInfo',
      get: async ({get}) => {
        cleanup?.();
        const controller = new AbortController();
        const signal = controller.signal;
        cleanup = () => controller.abort();
    
        const req = await fetch(`/user?id=${get(currentUserIDState)}`, {signal});
        return await req.json();
      },
    });
})();

Thanks for reading!

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:15
  • Comments:17 (7 by maintainers)

github_iconTop GitHub Comments

10reactions
buhichancommented, Oct 30, 2020

You are re-inventing rxjs’s switchMap, why not just use rxjs and stop using this lib once and for all? And why this library not choose observable which can carry more information (like subscription) than Promise? There’s no need to re-invent observable.

5reactions
steve-taylorcommented, May 20, 2020

Search-as-you-type is an example of where requests should be cancelled, even after debouncing. And you’re unlikely to get a lot of cache hits.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Cancel Pending API Requests to Show Correct Data
The solution. Turns out there is a way to abort pending DOM asynchronous requests using an AbortController . You can use it to...
Read more >
Canceling HTTP Requests in ASP.NET Core with ...
To cancel a request, we can use two methods: Cancel() , which cancels the request immediately, and CancelAfter() . For this example, we...
Read more >
A Pattern For Cancelling Fetch API Requests - codetinkerer.com
Async Cancellation ​​ Here is what that looks like using the fetch API: let abortController = new AbortController(); const loadData = async (url) ......
Read more >
API (REST) - Cancel API requests - JavaScript - Amplify Docs
You may cancel any request made through API category by keeping a reference to the promise returned.
Read more >
Making Cancel-able HTTP Requests with JavaScript Fetch API
We can use the AbortController to create cancellable HTTP requests. To do this, we create a new AbortController using the AbortController.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found