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

154
Views
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 answers
Answer question

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 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!