Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

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

By M.K. Verma · 3 May 2022

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/>)