Edison D'souza
Edison D'souza

Reputation: 4640

What happens if we call an async function inside render method?

We do not use redux or saga and use services instead, for making API calls and storing data. Consider that there is a button that will make an async call when clicked.

  1. Is it safe to call the async function inside the render method?
  2. Would it make the UI unresponsive until the promise is resolved?
render() {
    return (
        <Button onPress={() => {await this.requestOtp()}} text="Get OTP" />
    );
}

Upvotes: 0

Views: 1744

Answers (2)

David Vittori
David Vittori

Reputation: 1196

Render can not be async you can pass the async to componentDidMount or use hooks

Upvotes: 0

dougdf
dougdf

Reputation: 21

Try to use hooks:

import React, { useState } from 'react';

function MyComponent(){

 let [output, updateOutput] = useState(null);

 async function asyncFunction(){

  // call here
  let response = await this.requestOtp();
  updateOutput(response.data);

 }

 return <Button onPress={asyncFunction} text={output} />

}

Upvotes: 1

Related Questions