Earlier quoted context omitted.
It's supposed to run provided promise and return its status. If deps changed or component is unmounted while promise is pending, it should inform currently running promise using AbortSignal. And it should handle edge cases (e.g. promise is changed, second promise is started but first promise ignored abort signal and resolved to a value. This value should be ignored). Basically it should remove any boilerplate from us…
Thanks. But what do you use it for? What promises do you want your components to be involved with and in what way?
function Item({id}) {
const r = usePromise(async (signal) => {
const resp = await fetch(`/item/${id}`, {signal});
return await resp.json();
}, [id]);
if (r.status == "pending") {
return Loading;
}
if (r.status == "rejected") {
return Error: {r.reason};
}
return {r.value};
}
It's really like useEffect but provides better support for cancellation and properly tracks promise. Rewriting this snippet with useEffect correctly would require quite a lot of code (although rewriting this snippet with useEffect incorrectly is possible with not a lot of code, but you don't want to write incorrect code). Which has to be repeated everywhere.Again, this task is better solved by react-query or its alternatives. What I'm writing is not strictly web-site, but rather a web-interface on embedded device and web-server is not remote web-server but thing that works on the same device, so for now I decided not to use those libraries which made for slightly different use-cases.