Home > Software engineering >  How to wait for query to end in aws amplify
How to wait for query to end in aws amplify

Time:10-15

I query 'product' on one of my screens using the following function

const getProduct = async () => {

try{
      if(userId){
await DataStore.query(Product, c=>c.userID("eq", userId)).then(setProducts)
}
    }catch(e){
      return
    }
  };

But what I want is to display something like an activity indicator and wait for the query to finish and then display the products. How can I do this?

CodePudding user response:

Your code above should be inside a useEffect() hook that will run any time the userId changes. That hook can return multiple states: loading, error, the data...

To get the above in a very well tested, easier to read, package with bells & whistles (e.g. caching), look into React Query.

Pseudo-code:

function ExampleComponent() {
  const { isLoading, error, data } = useQuery(['products'], () =>
    // fetch data here
  )

  if (isLoading) return 'Loading...'

  if (error) return 'An error has occurred: '   error.message

  return (
    <div>
      <!-- map over your data here -->
    </div>
  )
}

CodePudding user response:

There is nothing extra needed to enable indicator, it's just a visual representation on the client to show that request is in progress. You can enable indicator before query and set it disabled within the setProducts

  • Related