Search code examples
javascriptreactjsapiasynchronoususe-effect

How to make an api call before component render in react js


  export default function Dashboard(){
      useEffect(() => {
          setTimeout(()=>console.log("API Call Completed"),5000)
      },[])

      return(
          <div>
            <h1>Dashboard</h1>
          </div>
      )
}

I want "API Call Completed" to be printed on console before Dashboard is printed on the page(or before return). But the msg gets printed on console 5 secs "Dashboard" appears on the page. How do I achieve this?


Solution

  • You can't.

    Rendering is designed to be non-blocking.

    There is no way to have it wait for something asynchronous to complete.


    Generally the approach would be to have an initial state and then update the state from the API call's callback.

    The render function can then, for example, detect the initial state and render a loading spinner.