Trying call useQuery in function with react-apollo-hooks

ko_ma picture ko_ma · Jul 10, 2019 · Viewed 16.2k times · Source

I want to call useQuery whenever I need it,

but useQuery can not inside the function.

My trying code is:

export const TestComponent = () => {
...
  const { data, loading, error } = useQuery(gql(GET_USER_LIST), {
    variables: {
      data: {
        page: changePage,
        pageSize: 10,
      },
    },
  })
  ...
  ...
  const onSaveInformation = async () => {
    try {
      await updateInformation({...})
      // I want to call useQuery once again.
    } catch (e) {
      return e
    }
}
...

How do I call useQuery multiple times?

Can I call it whenever I want?

I have looked for several sites, but I could not find a solutions.

Answer

Yusufbek picture Yusufbek · Jan 2, 2020

From apollo docs

When React mounts and renders a component that calls the useQuery hook, Apollo Client automatically executes the specified query. But what if you want to execute a query in response to a different event, such as a user clicking a button?

The useLazyQuery hook is perfect for executing queries in response to events other than component rendering

I suggest useLazyQuery. In simple terms, useQuery will run when your component get's rendered, you can use skip option to skip the initial run. And there are some ways to refetch/fetch more data whenever you want. Or you can stick with useLazyQuery

E.g If you want to fetch data when only user clicks on a button or scrolls to the bottom, then you can use useLazyQuery hook.