Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 71 ยท Projects

Project: Jokes Generator and Dictionary App

Build two API-driven React Native apps, a jokes generator and a dictionary with audio, and learn loading, error and empty states, stale-request guards and safe parsing.

Many first "real" apps are one screen that asks a web API a question and shows the answer: a joke, a word's meaning, the weather. They look easy, but they contain the three problems that every networked screen has: what to show while waiting, what to show when it fails, and what to do when answers arrive out of order. This lesson builds a jokes app and a dictionary app, and the parts that matter are the ones you can test without the network.

What runs on this site. The React Native screens, the real network calls and audio playback are read-only. The runnable examples use a fake API that answers with realistic JSON shapes after a short delay, so you can see loading, success, error and out-of-order responses.

A status you can reason about

Instead of several booleans (loading, error, data) that can contradict each other, keep one status and the data that goes with it:

JavaScript
// 'idle' | 'loading' | 'success' | 'error'
const [state, setState] = useState({ status: 'idle', data: null, error: null });

Every transition is explicit: starting a request sets loading, a good response sets success with data, a failure sets error with a message. The screen then renders by status, with no impossible combinations like "loading and error at the same time". This is the same design as in Networking with fetch.

Project 1: jokes generator

The screen has a joke area and a Get a joke button. Public joke APIs usually return one of two shapes: a single line ({ type: 'single', joke: '...' }) or a two-part joke ({ type: 'twopart', setup: '...', delivery: '...' }). Normalize them to one shape right after fetching, so the UI never has to care:

JavaScript
export function normalizeJoke(payload) {
  if (!payload || typeof payload !== 'object') throw new Error('Unexpected response');
  if (typeof payload.joke === 'string') return { setup: payload.joke, punchline: null };
  if (typeof payload.setup === 'string' && typeof payload.delivery === 'string') {
    return { setup: payload.setup, punchline: payload.delivery };
  }
  throw new Error('Unexpected response');
}

getJoke fetches and normalizes:

JavaScript
async function getJoke() {
  setState({ status: 'loading', data: null, error: null });
  try {
    const res = await fetch('https://jokes.example.com/joke/Any?safe-mode');
    if (!res.ok) throw new Error('Server error ' + res.status);
    setState({ status: 'success', data: normalizeJoke(await res.json()), error: null });
  } catch (e) {
    setState({ status: 'error', data: null, error: e.message });
  }
}

Two product choices improve the app: ask for a safe filter where the API offers one (a jokes app for everyone should not surprise people), and show the punchline only after a tap, which is one boolean (revealed) that resets on each new joke.

Project 2: dictionary

The dictionary lets the user type a word and shows its phonetic spelling, parts of speech, definitions, examples and a button that plays the pronunciation. A typical dictionary API returns an array of entries, each with meanings, and a 404 with a { title: 'No Definitions Found' } body for unknown words.

JavaScript
export function parseEntry(payload) {
  const entry = Array.isArray(payload) ? payload[0] : null;
  if (!entry) throw new Error('No entry');
  const audio = (entry.phonetics || []).map((p) => p.audio).find(Boolean) || null;
  return {
    word: entry.word,
    phonetic: entry.phonetic || (entry.phonetics || []).map((p) => p.text).find(Boolean) || '',
    audio,
    meanings: (entry.meanings || []).map((m) => ({
      partOfSpeech: m.partOfSpeech,
      definitions: (m.definitions || []).slice(0, 3).map((d) => ({ text: d.definition, example: d.example || null })),
    })),
  };
}

The function is defensive on purpose: fields can be missing, phonetics can be an empty array, and the audio URL is often an empty string. Parsing in one place with optional fallbacks keeps the screen free of ?. chains.

Search: trim, validate, encode

JavaScript
async function search(raw) {
  const word = raw.trim().toLowerCase();
  if (!word) return setState({ status: 'error', data: null, error: 'Type a word first.' });
  setState({ status: 'loading', data: null, error: null });
  try {
    const res = await fetch('https://dictionary.example.com/entries/en/' + encodeURIComponent(word));
    if (res.status === 404) throw new Error(`No definitions found for "${word}".`);
    if (!res.ok) throw new Error('Server error ' + res.status);
    setState({ status: 'success', data: parseEntry(await res.json()), error: null });
  } catch (e) {
    setState({ status: 'error', data: null, error: e.message });
  }
}

encodeURIComponent matters: a word like a/b or cafรฉ must be escaped before it goes into a URL. Treat "not found" as a normal outcome with a friendly message, not as a crash.

Pronunciation audio

Playing the audio needs a native audio module (expo-audio, or expo-av in older projects):

JSX
import { useAudioPlayer } from 'expo-audio';

function Pronounce({ uri }) {
  const player = useAudioPlayer(uri);
  return <Button title="Play" onPress={() => { player.seekTo(0); player.play(); }} />;
}

Show the button only when entry.audio exists. Audio URLs are remote files, so the first play may take a moment; a short loading state avoids the feeling that the button is broken.

The race: stale responses

The classic bug in search screens: the user searches "cat", then quickly "dog". The "dog" response arrives first, and then the slower "cat" response arrives and overwrites it. The screen shows cat's meaning under a "dog" search box. The fix is to remember which request is the latest, and ignore answers from older ones:

JavaScript
const latest = useRef(0);

async function search(word) {
  const id = ++latest.current;               // this request's number
  setState({ status: 'loading', data: null, error: null });
  try {
    const data = await fetchEntry(word);
    if (id !== latest.current) return;       // a newer search started; drop this answer
    setState({ status: 'success', data, error: null });
  } catch (e) {
    if (id !== latest.current) return;
    setState({ status: 'error', data: null, error: e.message });
  }
}

AbortController is the alternative: cancel the previous request when a new one starts (see Networking with fetch). The counter approach works with any promise, including a library call that cannot be aborted.

Jokes and dictionary against a fake API, with a stale-response guard

Press Get a joke three times: the first is a single line, the second is a setup with a "Reveal" button, and the third is a malformed response that ends in a friendly error with Retry. In the dictionary, "cat then dog fast" shows the race: both lists start a search for cat (slow, 900 ms) and then dog (fast, 200 ms). The unguarded one ends on cat's answer; the guarded one correctly ends on dog.

Polishing both apps

  • Debounce an as-you-type dictionary search by 300 ms, and still apply the stale-response guard.
  • Remember recent words with AsyncStorage and offer them as chips.
  • Cache answers in memory (a Map of word to entry) so a repeated word does not hit the network.
  • Accessibility: announce results with a live region, and make the reveal button describe what it does.
  • Content: for a general audience, request the API's safe mode, and do not store or log what people search for without telling them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why keep one status ('idle', 'loading', 'success', 'error') instead of separate loading and error booleans?

    A single status makes every screen state explicit and removes contradictory combinations.
  2. 2. A user searches 'cat' then 'dog' quickly, and the cat answer arrives last. How do you prevent the screen from showing cat?

    A request counter (or AbortController) lets you drop stale responses.
  3. 3. Why normalize the jokes API's two response shapes right after fetching?

    Parsing at the edge keeps the screens simple and puts the defensive checks in one testable function.
  4. 4. Why is encodeURIComponent used when building the dictionary URL?

    User text can contain characters with special meaning in a URL. Encoding makes the request correct and safe.

Summary

  • Model a request with one status (idle, loading, success, error) plus data and error, and render by status.
  • Normalize and defensively parse API responses in one function; treat "not found" as a normal result with a friendly message.
  • Encode user text in URLs, and handle empty input before calling the network.
  • Guard against stale responses with a request id or AbortController.
  • Audio, retry buttons, debounce and caching are small additions that make API apps feel finished.

Next: Project: Password Manager and Password Validator.