Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

queries.md

104 lines2.3 KB

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

export class TodosComponent {
  readonly todosQuery = injectQuery(() => ({
    queryKey: ['todos'],
    queryFn: fetchTodoList,
  }))
}
todosQuery = injectQuery(() => ({
  queryKey: ['todos'],
  queryFn: fetchTodoList,
}))
@Component({
  selector: 'todos',
  template: `
    @if (todosQuery.isPending()) {
      <span>Loading...</span>
    } @else if (todosQuery.isError()) {
      <span>Error: {{ todosQuery.error()?.message }}</span>
    } @else {
      <!-- We can assume by this point that status === 'success' -->
      @for (todo of todosQuery.data(); track todo.id) {
        <li>{{ todo.title }}</li>
      } @empty {
        <li>No todos found</li>
      }
    }
  `,
})
export class PostsComponent {
  readonly todosQuery = injectQuery(() => ({
    queryKey: ['todos'],
    queryFn: fetchTodoList,
  }))
}

If booleans aren't your thing, you can always use the status state as well:

@Component({
  selector: 'todos',
  template: `
    @switch (todosQuery.status()) {
      @case ('pending') {
        <span>Loading...</span>
      }
      @case ('error') {
        <span>Error: {{ todosQuery.error()?.message }}</span>
      }
      <!-- also status === 'success', but "else" logic works, too -->
      @default {
        <ul>
          @for (todo of todosQuery.data(); track todo.id) {
            <li>{{ todo.title }}</li>
          } @empty {
            <li>No todos found</li>
          }
        </ul>
      }
    }
  `,
})
class TodosComponent {}