|
|
|
|
|
by vbezhenar
1232 days ago
|
|
For example HTTP request. Anything, actually. Some rough code: 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 <div>Loading</div>;
}
if (r.status == "rejected") {
return <div>Error: {r.reason}</div>;
}
return <div>{r.value}</div>;
}
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. |
|