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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *