Background Fetching Indicators

A query's status === 'pending' state is sufficient enough to show the initial hard-loading state for a query, but sometimes you may want to display an additional indicator that a query is refetching in the background. To do this, queries also supply you with an isFetching boolean that you can use to show that it's in a fetching state, regardless of the state of the status variable:

ts
@Component({
  selector: 'posts',
  template: `
    @switch (query.status()) {
      @case ('pending') {
        Loading...
      }
      @case ('error') {
        An error has occurred: {{ query.error()?.message }}
      }
      @default {
        @if (query.isFetching()) {
          Refreshing...
        }
        @for (todo of query.data()) {
          <todo [todo]="todo" />
        }
      }
    }
  `,
})
export class TodosComponent {
  todosQuery = injectQuery(() => ({
    queryKey: ['todos'],
    queryFn: fetchTodos,
  }))
}
@Component({
  selector: 'posts',
  template: `
    @switch (query.status()) {
      @case ('pending') {
        Loading...
      }
      @case ('error') {
        An error has occurred: {{ query.error()?.message }}
      }
      @default {
        @if (query.isFetching()) {
          Refreshing...
        }
        @for (todo of query.data()) {
          <todo [todo]="todo" />
        }
      }
    }
  `,
})
export class TodosComponent {
  todosQuery = injectQuery(() => ({
    queryKey: ['todos'],
    queryFn: fetchTodos,
  }))
}

Displaying Global Background Fetching Loading State

In addition to individual query loading states, if you would like to show a global loading indicator when any queries are fetching (including in the background), you can use the useIsFetching hook:

ts
import { injectIsFetching } from '@tanstack/angular-query-experimental'

@Component({
  selector: 'global-loading-indicator',
  template: `
    @if (isFetching()) {
      <div>Queries are fetching in the background...</div>
    }
  `,
})
export class GlobalLoadingIndicatorComponent {
  isFetching = injectIsFetching()
}
import { injectIsFetching } from '@tanstack/angular-query-experimental'

@Component({
  selector: 'global-loading-indicator',
  template: `
    @if (isFetching()) {
      <div>Queries are fetching in the background...</div>
    }
  `,
})
export class GlobalLoadingIndicatorComponent {
  isFetching = injectIsFetching()
}
Want to Skip the Docs?
Query.gg - The Official React Query Course
“This course is the best way to learn how to use React Query in real-world applications.”—Tanner Linsley
Check it out