Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry

How to use data of an Async function inside a functional component to render HTML in js ?

How to use data of an Async function inside a functional component to render HTML in js ?

You should use a combination or useEffect and useState

You should use useEffect to launch the async get, without launching it each rerendering. If a async function is used to get some data from outside the component, this is called 'side effect' so use useEffect.

You should use useState to react to changes on theses side effects, re-rendering the component to get the data in the dom.

In the next example, Im using a dummy async function getGenres which returns an array of genres.

 const {useState, useEffect} = React;


async function getGenres() {

    var promise = new Promise(function(resolve, reject) {
     window.setTimeout(function() {
       resolve( ['genre1', 'genre2']);
     });
   });
   return promise;
   
}

const Screen = () => {
  const [genres, setGenres] = useState([])

  useEffect(
     () => {
        getGenres().then(
        res => setGenres(res)
      )
    }, [getGenres]
  )
  
  
  return (
    <ul>
      {
      genres.map(
        i => <li>{i}</li>
      )
      }
    </ul>
  );
}


const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<Screen/>)

6 0

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online