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.
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.
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.
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.
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 ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With