skip to Main Content

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?

2

Answers


  1. 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>
      )
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search