Documentation

fetchQuery

stable

Execute a fetch operation

Execute a fetch operation programmatically without React hooks. Perfect for one-time operations and event handlers usage.

Core APIPromise-based

Cache Integration

fetchQuery updates the cache, so any components using useQuery with the same key will automatically re-render with the new data.

Signature

function fetchQuery<TData, TError = Error>(
queryKey: QueryKey,
options?: QueryOptions<TData, TError>
): Promise<TData>

Parameters

queryKey

QueryKeyRequired

Unique identifier for the query. Can be a string, array, or object.

options

QueryOptions<TData, TError>

Optional configuration object. If no fetcher is provided, uses a previously registered fetcher.

options.fetcher

() => Promise<TData>

Function that returns a Promise resolving to the data. Optional if fetcher was already registered.

options.staleTime

numberDefault: 0

Time in milliseconds after which data is considered stale.

Returns

Returns

Promise<TData>

Promise that resolves to the fetched data

Examples

With Fetcher

Execute a one-time fetch operation with inline fetcher

import { fetchQuery } from 'qortex-react';
async function handleSubmit() {
try {
const result = await fetchQuery(
'submit-form',
{
fetcher: async () => {
const response = await fetch('/api/submit', {
method: 'POST',
body: JSON.stringify(formData)
});
return response.json();
}
}
);
console.log('Form submitted:', result);
} catch (error) {
console.error('Submission failed:', error);
}
}

Using Registered Fetcher

Use fetchQuery with a previously registered fetcher

import { fetchQuery, registerFetcher } from 'qortex-react';
// First, register a fetcher
registerFetcher('user-data', {
fetcher: async () => {
const response = await fetch('/api/user');
return response.json();
}
});
function RefreshButton() {
const handleRefresh = async () => {
try {
// No need to provide fetcher - uses registered one
await fetchQuery('user-data');
// Data is now cached and will update all components using this query
console.log('Data refreshed!');
} catch (error) {
console.error('Refresh failed:', error);
}
};
return (
<button onClick={handleRefresh}>
Refresh Data
</button>
);
}

Behavior

One-time Execution

Executes the fetch operation once and returns the result

Cache Integration

Updates the cache, affecting all components using the same query key

Error Handling

Throws errors that can be caught with try/catch

Promise-based

Returns a Promise for async/await or .then() usage

Best Practices

Do's

  • Use for one-time operations like form submissions
  • Handle errors with try/catch blocks
  • Use in event handlers code
  • Combine with useQuery for reactive updates

Don'ts

  • Don't use in render functions (use useQuery instead)
  • Don't forget to handle Promise rejections
  • Don't use for continuous data fetching
  • Don't use without proper error handling