fetch method

Future<void> fetch({
  1. bool force = false,
})

Fetches data for the query.

force set to true will bypass cache and force a network fetch.

Implementation

Future<void> fetch({bool force = false}) async {
  if (_disposed || !config.enabled) return;

  // Prevent multiple concurrent fetches unless forced
  if (state.status == QueryStatus.loading && !force) {
    return;
  }

  // If we have data and it's not stale, and not forced, do nothing.
  // This check is mainly for initial load. Subsequent fetches will be handled by `_isStale`.
  if (!force && state.hasData && !state.isStale) {
    return;
  }

  // Set loading state (keep previous data if exists)
  _updateState(QueryState.loading(state.data));

  try {
    final data = await _fetchWithRetry();

    // Cache and update state
    await _cache.set(queryKey.toString(), data, ttl: config.cacheTime);
    if (!_disposed) {
      _updateState(QueryState.success(data));
    }
  } catch (error) {
    debugPrint('Error fetching ${queryKey.toString()}: $error');
    if (!_disposed) {
      _updateState(QueryState.error(error, state.data));
    }
  }
}