Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying call useQuery in function with react-apollo-hooks

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.

like image 432
ko_ma Avatar asked Jul 10 '19 06:07

ko_ma


People also ask

How do you call a useQuery in React?

To run a query within a React component, call useQuery and pass it a GraphQL query string. When your component renders, useQuery returns an object from Apollo Client that contains loading , error , and data properties you can use to render your UI.

Is useQuery a hook?

useQuery is a hook that makes the GraphQL query as a side-effect and returns data , loading and error which contain the GraphQL response, the request state and the request error respectively. It also caches the data in memory so that whenever useQuery is called again, the data from this cache is used.

What is the difference between useQuery and useLazyQuery?

This hook acts just like useQuery , with one key exception: when useLazyQuery is called, it does not immediately execute its associatedquery. Instead, it returns a function in its result tuple that you can call whenever you're ready to execute the query.

Does useQuery run on Rerender?

The useQuery hook will make one fetch request on initial load, and will not refetch on subsequent renders. The useQuerey hook will trigger a re-render when it receives a response from the graphql backend (whether that response is data or an error ).


1 Answers

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.

like image 108
Yusufbek Avatar answered Sep 23 '22 13:09

Yusufbek