Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
await function returns a promise and returns true even if the condition is false | React Functional Component

In my JSX file, I have a function like this.

async isPresent () {
    const res = await AsyncFunction();
    if (res) {
        return true;
    }
    return false;
}

and then using it in a conditional rendering as

{  this.isPresent() &&  <div> Content </div> }

But this always returns true.

How do I solve this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can do:

const [isPresentResult, setIsPresentResult] = useState(false);

useEffect(() => {
  this.isPresent().then(res => setIsPresentResult(res))
}, [])

// ...
{ isPresentResult &&  <div> Content </div> }

Using Class Component:

class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isPresentResult: false };
  }

  componentWillMount = () => {
    this.isPresent().then((isPresentResult) => 
      this.setState({ isPresentResult }));
  };

  async isPresent() {
    const res = await AsyncFunction();
    return !!res;
  }

  render() {
    return {this.state.isPresentResult && <div> Content </div>};
  }
}
about 4 years ago · Juan Pablo Isaza Report

0

You cannot have asynchronous logic in render. You need to extract the present boolean into a state and make the asynchronous call inside something like componentDidMount and then update the present state from there.

Refer to the example below:

const sleep = (delay) => new Promise(res => setTimeout(() => res(true), delay))

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      present: false,
    };
  }

  componentDidMount() {
    sleep(1000).then((res) => {
      if (res) {
        this.setState({ present: true });
      }
    });
  }

  render() {
    return <div>{this.state.present ? "Present": "Not Present"}</div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!