Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Forms and Data

Fetching Data in Ionic: HTTP, Loading and Pull to Refresh

Load remote data in Ionic apps with fetch, HttpClient or composables, handle loading, empty and error states, cancel requests, and add ion-refresher.

Nearly every app shows remote data. Ionic does not include an HTTP client: you use the standard fetch API or your framework's tools (Angular HttpClient, React hooks, Vue composables). What Ionic adds is the UI: skeleton text for loading, ion-refresher for pull to refresh, and the page lifecycle that decides when to fetch. This lesson builds the full loading, empty, error and success flow and makes it robust.

The four states of every list

Every data view is in exactly one state:

Four states

Loading Show skeletons
Success Show the data
1 / 2

Modelling them explicitly avoids contradictory flags such as loading = true and error = true at once.

JS Stand-in: a request state machine

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Fetching with fetch

TypeScript
export interface Note { id: number; title: string; }

export async function getNotes(signal?: AbortSignal): Promise<Note[]> {
  const res = await fetch('https://api.example.com/notes', { signal });
  if (!res.ok) throw new Error(`Request failed: ${res.status}`);
  return res.json();
}

fetch only rejects on network failure, not on HTTP errors like 404 or 500. Always check res.ok. On Angular, HttpClient returns an Observable and throws on non-2xx status codes by itself, which many teams prefer; use interceptors for auth headers and error handling.

When to fetch

Pages stay alive in the stack (lifecycle lesson). Choose the hook by need:

  • Fetch once on creation for static data.
  • Fetch in ionViewWillEnter when the data may change while the page is covered.
  • Re-fetch on pull to refresh.

Skeleton loading

Instead of a spinner, show the shape of the content with ion-skeleton-text:

HTML
<ion-list *ngIf="loading">
  <ion-item *ngFor="let n of [1,2,3,4]">
    <ion-label>
      <h3><ion-skeleton-text [animated]="true" style="width: 60%"></ion-skeleton-text></h3>
      <p><ion-skeleton-text [animated]="true" style="width: 90%"></ion-skeleton-text></p>
    </ion-label>
  </ion-item>
</ion-list>

Skeletons make loading feel faster because the layout does not jump when data arrives.

Pull to refresh

HTML
<ion-content>
  <ion-refresher slot="fixed" (ionRefresh)="refresh($event)">
    <ion-refresher-content pullingText="Pull to refresh" refreshingText="Loading..."></ion-refresher-content>
  </ion-refresher>
  <ion-list>...</ion-list>
</ion-content>
TypeScript
async refresh(event: any) {
  try {
    this.notes = await getNotes();
  } finally {
    event.target.complete(); // always end the refresher animation
  }
}

The refresher stays in its loading state until you call complete(). Put it in finally so an error does not leave it spinning forever. It works with touch and, in recent versions, with mouse drag on desktop.

Cancelling and ignoring stale responses

If the user changes a filter quickly, an older request may finish after a newer one and overwrite the right result (a race condition). Two cures:

  • Abort the old request with AbortController.
  • Ignore a response whose request id is not the latest.
JS Stand-in: ignore stale responses

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Caching and offline

Mobile networks are unreliable. A simple in-memory cache with a time to live avoids repeating requests; real offline support comes with storage in chapter 6. This stand-in shows a cache with expiry:

JS Stand-in: a cache with a time to live

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Error handling that helps

  • Distinguish "offline" from "server error" and say which.
  • Offer a Retry button next to the message.
  • Log technical details; show friendly text.
  • For auth failures (401), redirect to login rather than showing an error.
TypeScript
function describeError(e: unknown): string {
  if (!navigator.onLine) return 'You are offline. Check your connection.';
  if (e instanceof Error && /\b5\d\d\b/.test(e.message)) return 'The server had a problem. Try again shortly.';
  return 'Something went wrong. Please try again.';
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does fetch do on a 404 response?

    fetch only rejects for network failures; HTTP errors resolve with ok = false.
  2. 2. Why call event.target.complete() inside finally?

    Otherwise an error would leave the pull-to-refresh spinner running.
  3. 3. What problem does an AbortController solve?

    It cancels requests whose results are no longer needed, avoiding races.
  4. 4. Which are the four states of a data view?

    Design all four states.

Summary

  • Model loading, success, empty and error states explicitly.
  • Check res.ok with fetch; Angular HttpClient throws on non-2xx.
  • Pick the right moment to fetch: creation, ionViewWillEnter, refresh.
  • Use skeletons, ion-refresher with complete() in finally, and ignore or abort stale requests.
  • Cache briefly and show helpful error messages with a retry.

Next: Searchbar, Filtering and Infinite Scroll