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

157
Visualizações
React & Javascript - render field based on the result of an async function

I have an async function and want to use it to query and return a value, something like this:

  async function checkProfileFeature(values: any) {
    const data = await client.query<any>({
      query: PROFILE_QUERY,
      variables: { userId: 1, profileId: values.id },
    });

    if(something) {
      return true
    }
  } 

Based on this return value I want to display or not display a field:

  {checkProfileFeatures(profile) === true && (
    <Input .... />
  )}

Unfortunately I can't get it to return the value and display the field on its result at the same time. Is there a recommended way to do this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

checkProfileFeature has a async keyword on it which basically means it will return a Promise, in your case Promise<boolean | undefined> (since you return true only if a certain condition is met). checkProfileFeatures(profile) === true will never be true because, as I already mentioned, your function returns a Promise. What you want to do is put your checkProfileFeatures inside a useEffect and then store results of the query inside a store of some kind or useState

// Run on first render
useEffect(() => {
 const fetchQuery = async () => {
  await checkProfileFeature({});
 }

 fetchQuery();
}, [])

Then, inside checkProfileFeature save your results

async function checkProfileFeature(values: any) {
    const data = await client.query<any>({
      query: PROFILE_QUERY,
      variables: { userId: 1, profileId: values.id },
    });

    if(something) {
      setSomethingHappened(true);
    }
  } 

And in return body you can use this fetched value

{somethingHappened === true && (
    <Input .... />
  )}

Of course you still need to figure out how to handle loading state, you may want to create an additional state which will tell whether the request is still running.

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