Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda