Home > Enterprise >  React & Javascript - render field based on the result of an async function
React & Javascript - render field based on the result of an async function

Time:02-14

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?

CodePudding user response:

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.

  • Related