How to call useQuery as an async task

11,893

Apollo Client uses fetch which is always asynchronous. The issue is that you are creating an infinite loop.

  • The object returned by the useLazyQuery hook you are destructuring does not have properties named tempLoading, tempError or tempData. See here for how to correctly rename variables when using destructuring syntax.
  • Because tempData is always undefined, your useEffect hook's callback will be called on every render.
  • Calling loadData on every render triggers another render.

By using useLazyQuery, you are unnecessarily complicating your code -- you should be using useQuery instead.

const { data, loading } = useQuery(query)
if (loading) {
  return <View>....</View>
}
return <View>...</View>
Share:
11,893
Bindiya
Author by

Bindiya

Working as an iOS developer.

Updated on June 06, 2022

Comments

  • Bindiya
    Bindiya almost 2 years

    I am new to React Native and Apollo-Client. In my Screen there are three tabs and individual tabs is calling its own data. But due to useQuery UI is completely freezing and giving a very bad experience.

    Is there any other way that I can call the useQuery in async manner or in any background task?

    EDIT

    function PlayerList(props) {
    
        const [loading , setloading] = useState(true)
        const [data, setData] = useState()
        const [loadData, { tempLoading, tempError, tempData }] = useLazyQuery(query);
       
    
       async function getData(){
            loadData()
       }
    
        useEffect(() => {
    
            if (tempData == undefined) {
                getData()
            }
    
        })
    
         if(tempLoading){
               return 
                    <View >....</View>
         }
         if(tempData) {
              return ( <View> ... </View>) }
    
     }
    

    Please find the above code for better understanding.

    • Daniel Rearden
      Daniel Rearden over 4 years
      Apollo Client uses fetch under the hood, which is always asynchronous. It sounds like something else is going on. You should edit your question to include the relevant code.
    • Bindiya
      Bindiya over 4 years
      @DanielRearden , please look the edited one.
  • Bindiya
    Bindiya over 4 years
    Thanks for updating about Apollo Client being the asynchronous. My issue was my UI was not getting updated properly after fetching the data.