API Request - cancelation of asynchronous selector
See original GitHub issueThanks 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:
- Created 3 years ago
- Reactions:15
- Comments:17 (7 by maintainers)
Top GitHub Comments
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.
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.