Categories
React Answers

How to render React components with promises inside the render method?

Spread the love

Sometimes, we want to render React components with promises inside the render method.

In this article, we’ll look at how to render React components with promises inside the render method.

How to render React components with promises inside the render method?

To render React components with promises inside the render method, we use the react-promise library.

To install it, we run

npm i react-promise

Then we use it by writing

import usePromise from "react-promise";

const ExampleWithAsync = (props) => {
  const { value, loading } = usePromise(prom);
  if (loading) {
    return null;
  }
  return <div>{value}</div>;
};

We call the usePromise hook with the prom promise.

And we get the resolve value of prom from value.

If loading is true, then prom is being run.

Conclusion

To render React components with promises inside the render method, we use the react-promise library.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.