Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 71 ยท Projects

Project: Weather App

Build a React Native weather app with fetch, a four-state request model, a search input, pull to refresh and stale-response protection, with a mocked API stand-in.

The weather app is the classic first project that talks to a server. The interface is simple (type a city, see a temperature), but the interesting part is everything that can go wrong: the network is slow, the city does not exist, the user types again before the first answer arrives, or the phone is in a tunnel.

This project teaches you to model those situations on purpose. You will build a small request state machine (idle, loading, success, error), a search box, a pull-to-refresh gesture and a guard that throws away stale answers. It builds on Networking with fetch and SectionList, Pull to Refresh and Infinite Scroll.

What runs on this site. The real screen uses fetch, ScrollView and RefreshControl, so it is read-only here. The runnable examples use a mocked API: a function that returns a promise after a short delay with fixed data or a fixed error. The state logic is the real thing; the network and native pull gesture are stand-ins, and every number shown is invented sample data, not a real forecast.

Plan the states first

Beginners often keep three separate variables (loading, data, error) and then hit impossible combinations such as "loading and error at once". A better model is one status value that can only be in one state at a time.

One request, four states

idle Nothing requested yet.
loading Waiting for the server.
success We have data to show.
error Show a message and a retry.

The screen is a function of the status.

1 / 2

Note the difference between the second and third error kinds. fetch rejects only when the request itself fails (no connection, DNS failure, timeout you implement). A 404 or 500 response is a successful fetch with a bad status, so you must check response.ok yourself.

The data layer

Keep the network call in its own function so the screen never touches fetch directly. This is the real function, read-only here:

JavaScript
const BASE = 'https://api.example-weather.test/v1';

export async function fetchWeather(city, { signal } = {}) {
  const response = await fetch(BASE + '/current?city=' + encodeURIComponent(city), { signal });

  if (response.status === 404) {
    throw new Error('We could not find "' + city + '".');
  }
  if (!response.ok) {
    throw new Error('The weather service had a problem (' + response.status + ').');
  }

  const json = await response.json();
  return { city: json.city, tempC: json.temp_c, summary: json.summary };
}

encodeURIComponent matters: a city like "Sao Paulo" contains a space, and some names contain characters that would otherwise break the URL. The host in this example is a placeholder; a real app would use its provider's documented URL and keep any API key out of the bundle (see Mobile App Security).

The reducer for the status is tiny and pure:

JavaScript
export const initial = { status: 'idle', data: null, error: null };

export function weatherReducer(state, action) {
  switch (action.type) {
    case 'start':
      return { ...state, status: 'loading', error: null };
    case 'success':
      return { status: 'success', data: action.data, error: null };
    case 'failure':
      return { status: 'error', data: null, error: action.message };
    default:
      return state;
  }
}

On start we keep the old data. That allows a refresh to show the previous temperature while the new one loads, instead of flashing an empty screen.

Request states with a mocked API

Each search ends in exactly one terminal state, and the screen can be written as a simple switch on state.status. The three cases (found, 404, network failure) are the ones you should always test by hand in a real app too: turn on airplane mode and see what your screen does.

The screen

The real screen combines a TextInput, a button, a result card and a ScrollView with RefreshControl:

JSX
import { useReducer, useRef, useState } from 'react';
import { ActivityIndicator, Pressable, RefreshControl, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native';
import { fetchWeather } from './api';
import { initial, weatherReducer } from './weatherReducer';

export default function WeatherScreen() {
  const [state, dispatch] = useReducer(weatherReducer, initial);
  const [query, setQuery] = useState('');
  const [lastCity, setLastCity] = useState(null);
  const latest = useRef(0);

  async function load(city) {
    const id = ++latest.current;
    dispatch({ type: 'start' });
    try {
      const data = await fetchWeather(city);
      if (id === latest.current) dispatch({ type: 'success', data });
    } catch (e) {
      if (id === latest.current) dispatch({ type: 'failure', message: e.message });
    }
  }

  function search() {
    const city = query.trim();
    if (!city) return;
    setLastCity(city);
    load(city);
  }

  return (
    <ScrollView
      contentContainerStyle={styles.content}
      keyboardShouldPersistTaps="handled"
      refreshControl={
        <RefreshControl
          refreshing={state.status === 'loading' && state.data !== null}
          onRefresh={() => lastCity && load(lastCity)}
        />
      }
    >
      <TextInput
        style={styles.input}
        value={query}
        onChangeText={setQuery}
        onSubmitEditing={search}
        placeholder="City name"
        autoCapitalize="words"
        returnKeyType="search"
      />
      {state.status === 'loading' && !state.data ? <ActivityIndicator size="large" /> : null}
      {state.status === 'error' ? (
        <View>
          <Text style={styles.error}>{state.error}</Text>
          <Pressable onPress={() => lastCity && load(lastCity)}><Text>Try again</Text></Pressable>
        </View>
      ) : null}
      {state.data ? (
        <View style={styles.card}>
          <Text style={styles.city}>{state.data.city}</Text>
          <Text style={styles.temp}>{Math.round(state.data.tempC)}ยฐ</Text>
          <Text>{state.data.summary}</Text>
        </View>
      ) : null}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  content: { padding: 16, gap: 16 },
  input: { borderWidth: 1, borderColor: '#cbd5e1', borderRadius: 8, padding: 12, fontSize: 16 },
  error: { color: '#b91c1c', marginBottom: 8 },
  card: { backgroundColor: '#e0f2fe', borderRadius: 16, padding: 24, alignItems: 'center' },
  city: { fontSize: 20, fontWeight: '600' },
  temp: { fontSize: 56, fontWeight: '200' },
});

Three details are worth studying. RefreshControl only receives refreshing for a reload that already has data, so the spinner at the top of the list is the pull-to-refresh one, while the first search shows a centered ActivityIndicator. returnKeyType="search" puts a magnifier on the keyboard's action key. And latest is the race guard: each call gets a number, and only the newest call is allowed to update the screen.

The race condition

Imagine the user searches "Oslo", then quickly "Lima". Networks do not promise ordering: the Lima answer might arrive first and the Oslo answer second, leaving the screen showing Oslo under a search box that says Lima. The latest counter fixes this by ignoring any answer that is not from the most recent request. The alternative is AbortController: cancel the old request when starting a new one, which also saves bandwidth. Real apps often do both.

Weather app with search, refresh and a race guard

Run the experiment from the last paragraph with the guard on and then off. Seeing the wrong city appear under the wrong search is the clearest way to remember why the guard exists.

Finishing touches

  • Timeouts. fetch has no timeout of its own. Wrap it with an AbortController and setTimeout, and treat the abort as an error message such as "That took too long".
  • Debounced search-as-you-type needs the same race guard, plus a short delay so you do not call the server for every letter.
  • Units and locale. Format temperatures with Intl.NumberFormat (supported by Hermes) and let the user switch between Celsius and Fahrenheit.
  • Caching. Keep the last result in storage so the app shows something instantly on launch; Server State with TanStack Query automates this.
  • Emulator networking. The Android emulator reaches your computer at 10.0.2.2, not localhost, and plain HTTP needs explicit permission on both platforms.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A server answers a weather request with HTTP 404. What does fetch do by default?

    fetch rejects only when the request cannot complete at all. An HTTP error status is still a completed response, so you have to inspect it.
  2. 2. Why model the request with one status value instead of separate loading, data and error variables?

    A single status can hold only one state at a time, so the screen is a clear function of that status and cannot show contradictory UI.
  3. 3. What does the latest ref counter protect against?

    Each request remembers its number, and only the response matching the newest number may update state. Slow older answers are dropped.
  4. 4. Why does RefreshControl get refreshing only when data already exists?

    The first search has nothing to show, so an ActivityIndicator fits. For a refresh the old data stays visible and the pull-to-refresh spinner reports progress.

Summary

  • Model a request as one status (idle, loading, success, error) and let the screen switch on it.
  • fetch rejects on network failure only; always check response.ok for HTTP errors, and encode user input in URLs.
  • Guard against races with a request counter (or AbortController) so stale answers never reach the screen.
  • Use RefreshControl for pull to refresh, keep old data visible during a reload, and give errors a retry action.
  • On this site the native screen is read-only; the state machine and race guard run for real against a mocked API.

Next, add several screens and saved data in Project: Notes App with Navigation.