Search code examples
react-nativegraphqlreact-hooksapolloapollo-client

How to call useQuery as an async task


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.


Solution

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