Search code examples
compositionvue-apollo

How to manually call query (e.g. on click) using Vue Apollo Composible?


The default behavior is that useQuery is loaded immediately with component setup.

I want to trigger the query on some event like click.

How to do it?


Solution

  • i searched for it a lot too, but it is writtin in their documentation vue apollo v4e

    import { useQuery, useResult } from '@vue/apollo-composable'
    import gql from 'graphql-tag'
    
    export default {
      setup () {
        const { result, loading, error, refetch } = useQuery(<query>)
    
        const users = useResult(result)
    
        return {
          users,
          loading,
          error,
          refetch,
        }
      },
    }
    </script>
    
    <template>
      <div v-if="loading">Loading...</div>
    
      <div v-else-if="error">Error: {{ error.message }}</div>
    
      <ul v-else-if="users">
        <li v-for="user of users" :key="user.id">
          {{ user.firstname }} {{ user.lastname }}
        </li>
    
        <button @click="refetch()">Refresh</button>
      </ul>
    </template>
    

    just add the "refetch" to the useQuery line and call it from the button click event.

    EDIT: You could disable the query, so it wont trigger on component setup and on button click you could enable the query and refetch it.

    Best Regards