Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: Trail Weather and Nearby Places

Build an Ionic app that finds your location, fetches weather and nearby places, caches responses, handles loading and errors, and works with a saved last position.

This project builds a small utility app: it finds where the user is, shows the weather there, and lists the nearest saved trailheads. It looks simple, and it exercises what makes real apps hard: network calls that fail, slow responses, stale data, permissions and units. The result is an app that feels dependable even on a bad connection.

The weather service in this lesson is a stand-in object, so everything runs here. In your app you would replace it with fetch calls to a weather API of your choice, using its documented terms and your own API key stored on a server (never hard-code a secret key into a mobile app: anyone can extract it).

Screens and flow

flowchart TD
  A["App start"] --> B{"Saved last position?"}
  B -->|"Yes"| C["Show cached weather immediately"]
  B -->|"No"| D["Ask for location"]
  C --> E["Refresh in background"]
  D --> E
  E --> F{"Request ok?"}
  F -->|"Yes"| G["Update screen and cache"]
  F -->|"No"| H["Keep cached data, show 'Offline' note"]

Cached data first, fresh data when available, and never an empty screen if anything is known.

Step 1: a data layer with state

Every request has four states: idle, loading, success and error. Model them explicitly instead of using a few booleans, so that impossible combinations (loading and error at once) cannot occur.

JS Request state machine with a cache

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

No output.

Notice that an error keeps the stale data so the screen can still show something along with a banner.

Step 2: units and formatting

Users in different countries expect Celsius or Fahrenheit, kilometers or miles. Store values in one unit (metric) and convert in the view. Intl formats numbers and units for the user's locale.

JS Unit conversion and Intl formatting

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

No output.

Step 3: nearby places

The saved trailheads come from your own list (or an API). Rank them with the haversine distance from Geolocation, Device and Network and show the nearest five. To avoid recomputing on every GPS tick, recalculate only when the position changed by more than, say, 100 meters.

Step 4: the page

TypeScript
@Component({ /* standalone, imports: Ion components */ })
export class WeatherPage implements OnInit, OnDestroy {
  state = signal<WeatherState>({ status: 'idle' });
  private sub?: PluginListenerHandle;

  async ngOnInit() {
    const last = await load<Position | null>('lastPosition', null);
    if (last) this.refresh(last);                       // cached first
    this.sub = await Network.addListener('networkStatusChange', s => s.connected && this.refresh());
  }
  async refresh(pos?: Position) {
    const p = pos ?? await this.locate();
    await this.model.load(p);
  }
  async handleRefresh(ev: CustomEvent) { await this.refresh(); (ev.target as HTMLIonRefresherElement).complete(); }
  ngOnDestroy() { this.sub?.remove(); }
}

The template uses ion-refresher for pull to refresh, an ion-skeleton-text placeholder while loading, ion-note for "Updated 3 minutes ago" and an ion-toast or banner for errors. Use @switch (state().status) so each state has exactly one view.

Step 5: robustness

  • Timeouts: wrap fetch with an AbortController and a 8 to 10 second timeout; mobile networks can hang.
  • Retry automatically only on network errors and 5xx responses, with backoff. Do not retry 4xx.
  • Validate the response shape before using it; a changed API must not crash the page.
  • Secrets: call your own small backend that holds the API key.
  • Privacy: coordinates are personal data; send the minimum precision (round to two decimals) and say so in the privacy policy.
JS Timeout and retry wrapper

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

No output.

Stretch goals

  1. A 5 day forecast with a list and a chart.
  2. A home screen widget or notification at 7 am using a local notification.
  3. Favorites stored in Preferences with reordering via ion-reorder-group.
  4. Dark mode that follows the system, with a manual override.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why model request state as status values instead of separate booleans?

    One status field has exactly one value at a time.
  2. 2. What should the screen do when a refresh fails but cached data exists?

    Stale data is usually more helpful than nothing, as long as it is labelled.
  3. 3. Which failures are normally worth retrying?

    Temporary failures may succeed later; client errors will not change by repeating them.
  4. 4. Where should an API secret key live?

    Anything shipped in the app can be extracted, so a backend must hold and use the secret.

Summary

  • Show cached data first, refresh in the background, keep stale data on failure.
  • Model loading, success and error as explicit states.
  • Use Intl for units; store metric and convert in the view.
  • Add timeouts, selective retries and response validation.
  • Keep secrets on a server and minimize location precision.

Next: Ionic Practice Exercises