putCachedQuery<T> method

ZenQuery<T> putCachedQuery<T>({
  1. required Object queryKey,
  2. required ZenQueryFetcher<T> fetcher,
  3. Duration staleTime = const Duration(minutes: 5),
  4. T? initialData,
})

Register a scoped query with common caching defaults.

This is a convenience method that provides sensible defaults for cached data. It's equivalent to putQuery with a pre-configured ZenQueryConfig that sets the stale time.

Parameters:

  • queryKey: Unique identifier for the query
  • fetcher: Async function that fetches the data
  • staleTime: How long data is considered fresh (default: 5 minutes)
  • initialData: Optional initial data to show before first fetch

Returns: The created ZenQuery instance

Example:

// Data stays fresh for 5 minutes (default)
scope.putCachedQuery<Product>(
  queryKey: 'product:$id',
  fetcher: (_) => api.getProduct(id),
);

// Custom stale time for real-time data
scope.putCachedQuery<StockPrice>(
  queryKey: 'stock:AAPL',
  fetcher: (_) => api.getStockPrice('AAPL'),
  staleTime: Duration(seconds: 30), // Refresh more frequently
);

When to use:

  • ✅ Standard CRUD operations (user profiles, product details, etc.)
  • ✅ Data that doesn't change frequently
  • ✅ You want sensible caching without configuration

When to use putQuery instead:

  • ❌ You need more control (custom retry logic, background refetch, etc.)
  • ❌ Data changes frequently and needs shorter stale time
  • ❌ You want different cache vs stale time settings

See also: putQuery for full configuration options

Implementation

ZenQuery<T> putCachedQuery<T>({
  required Object queryKey,
  // CHANGED: Now accepts a ZenQueryFetcher (takes cancelToken)
  required ZenQueryFetcher<T> fetcher,
  Duration staleTime = const Duration(minutes: 5),
  T? initialData,
}) {
  return putQuery<T>(
    queryKey: queryKey,
    fetcher: fetcher,
    config: ZenQueryConfig(staleTime: staleTime),
    initialData: initialData,
  );
}