use-lazy-query
v1.0.3
Published
custom @tanstack/react-query hook - useLazyQuery
Maintainers
Readme
useLazyQuery
A custom React hook for lazy loading queries using @tanstack/react-query. It is inspired by Apollos useLazyQuery.
Installation
npm install use-lazy-queryUsage
import { useLazyQuery } from "use-lazy-query";
function useData() {
const [fetch, query] = useLazyQuery({
queryKey: ["data"],
queryFn: async (variables) => {
const response = await fetch(`/api/data?id=${variables.id}`);
return response.json();
},
options: {
...normalReactQueryOpts,
},
});
}
function MyComponent() {
const [fetch, query] = useData();
return <button onClick={() => fetch({ id: 1 })}>Load Data</button>;
}Parameters
| Parameter | Type | Required | Description | | --------- | -----------------------------------------------------------: | :------: | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------- | | queryKey | QueryKey (string | Array) | Yes | Unique key for the query (passed to react-query). | | queryFn | (variables?: any) => Promise | Yes | Async function that performs the fetch. Receives the variables object passed to the execute function. | | options | UseQueryOptions<T, E> & { initializeQueryOnMount?: boolean } | No | Any react-query options; supports initializeQueryOnMount to run on mount like useQuery. |
| Return | Type | Description | | ----------------- | ---------------------------------------------------------: | -------------------------------------------------------------------------------------------------------------------------------- | | [execute, result] | [(variables?: any) => Promise, UseQueryResult<T, E>] | execute triggers the query with optional variables; result is the current react-query result object (status, data, error, etc.). |
initializeQueryOnMount
If you want the query to execute at first mount, just like a normal useQuery, pass in the option initializeQueryOnMount.
But you still have the ability to execute the query on fetch.
import { useLazyQuery } from "use-lazy-query";
function useData(request: Request) {
const [execute, result] = useLazyQuery({
queryKey: ["data", request],
queryFn: async (variables) => {
const response = await fetch(`/api/data?id=${variables.id}`);
return response.json();
},
options: {
...normalReactQueryOpts,
initializeQueryOnMount: !!request,
},
});
}
function MyComponent() {
const request = buildReqest();
const [fetch, query] = useData(request); // when `request` is defined, the query will run on first mount – like a useQuery.
return <button onClick={() => fetch({ id: 1 })}>Load Data</button>;
}License
MIT
