Hacker News new | past | comments | ask | show | jobs | submit login

What does usePromise is supposed to do?



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 user of this API and handle edge cases.


Thanks. But what do you use it for? What promises do you want your components to be involved with and in what way?


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.


I think I'd go about it using redux-thunk because I feel like render function is not a great place for complex async state changes and chcecking internal status of a promise is a bit low level, but you've built a nice, easy to use thing. If you published it some people might find it to be exactly what they need. Plus they might help you debug some corner cases.


FYI, we recommend that most folks should not write promise management, data fetching, or loading status tracking code directly

If you're using just React, use React Query or something like `react-async`.

If you're using Redux, use the "RTK Query" data fetching and caching API in our official Redux Toolkit package:

- https://redux.js.org/usage/side-effects-approaches


Thanks, I'll think about it.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: