Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda