Thuta Learning
React Native
IntermediateMobile DevelopmentIntermediate

Fetching Data with API

React NativeLesson 1320 min

What you'll walk away with

  • Explain the React and native-platform behavior of Fetching Data with API
  • Test accessibility, failure, and lifecycle cases
  • Write maintainable, testable, and performant React Native

Explain it simply

Fetching Data with API, in plain language

In React Native, the fetch API is available with the same syntax as in a web browser (it's built in) — if you want the API call to run only once, when the component mounts, put it inside useEffect(() => { ... }, []) (an empty dependency array). Combine two useState calls — a loading state (to show while waiting for data) and an error state (to show on failure) — and you get a complete data-fetching pattern.

Problem → Why → Solution

The problem — why this concept matters

Leaving out useEffect's dependency array ([]) so the API call runs over and over on every render

A common mistake

Running a fetch call without try/catch, so a network error crashes the app

Core concept — understand how it works

Build Fetching Data with API as a lifecycle-aware flow covering permission, loading, empty, offline, timeout, cancellation, retry, foreground/background transitions, and stale data. Clean up subscriptions, timers, and requests.

Mental model
  1. request or permission
  2. native module boundary
  3. result, error, or cleanup

Explain the React and native-platform behavior of Fetching Data with API

Core syntax or pattern

javascript
import { useState, useEffect } from 'react';
import { View, Text, ActivityIndicator, FlatList } from 'react-native';

export default function PostsList() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
      .then((data) => setPosts(data))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <ActivityIndicator size="large" />;
  if (error) return <Text>Error: {error}</Text>;

  return (
    <FlatList
      data={posts}
      keyExtractor={(item) => item.id.toString()}
      renderItem={({ item }) => <Text>{item.title}</Text>}
    />
  );
}

Build Fetching Data with API as a lifecycle-aware flow covering permission, loading, empty, offline, timeout, cancellation, retry, foreground/background transitions, and stale data. Clean up subscriptions, timers, and requests.

Read the code step by step

  1. request or permissionimport { useState, useEffect } from 'react';

    In React Native, the fetch API is available with the same syntax as in a web browser (it's built in) — if you want the API call to run only once, when the component mounts, put it inside useEffect(() => { ... }, []) (an empty dependency array). Combine two useState calls — a loading state (to show while waiting for data) and an error state (to show on failure) — and you get a complete data-fetching pattern.

  2. native module boundary.finally(() => setLoading(false));

    Build Fetching Data with API as a lifecycle-aware flow covering permission, loading, empty, offline, timeout, cancellation, retry, foreground/background transitions, and stale data. Clean up subscriptions, timers, and requests.

  3. result, error, or cleanup}

    Test an original Fetching Data with API example on Android and iOS with small and large screens, font scaling, dark mode, keyboard and screen reader use, slow/offline networking, denied permissions, and background/foreground transitions. Use DevTools, tests, and a release build where relevant.

Execution flow
  1. request or permission
  2. native module boundary
  3. result, error, or cleanup

Success

Explain the React and native-platform behavior of Fetching Data with API

Failure

Leaving out useEffect's dependency array ([]) so the API call runs over and over on every render

Let's think about it this way for a second

In React Native, the fetch API is available with the same syntax as in a web browser (it's built in) — if you want the API call to run only once, when the component mounts, put it inside useEffect(() => { ... }, []) (an empty dependency array). Combine two useState calls — a loading state (to show while waiting for data) and an error state (to show on failure) — and you get a complete data-fetching pattern.

Let's connect this to a real-world scenario

Wrapping the API call in try/catch matters for error handling — when there's no network connection (mobile users lose signal all the time), fetch can throw, and without a catch the app can crash. Show the ActivityIndicator component (a built-in loading spinner) while the loading state is true, and render the actual content once the data has arrived.

Code Example

javascript
import { useState, useEffect } from 'react';
import { View, Text, ActivityIndicator, FlatList } from 'react-native';

export default function PostsList() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
      .then((data) => setPosts(data))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <ActivityIndicator size="large" />;
  if (error) return <Text>Error: {error}</Text>;

  return (
    <FlatList
      data={posts}
      keyExtractor={(item) => item.id.toString()}
      renderItem={({ item }) => <Text>{item.title}</Text>}
    />
  );
}
You should see
When the app opens, a loading spinner appears, and once the data arrives, the list of post titles is displayed in a FlatList.

Try it in 5 minutes

Fetch data from a public API (e.g. jsonplaceholder.typicode.com) and build a screen yourself that handles both the loading and error states.

A quick word of caution

Don't hardcode API keys or sensitive tokens in client code (remember the API Key Management lesson from the Cybersecurity tutorial) — decompiling a mobile app can expose hardcoded secrets.

Real-world usage

How to apply it in a real project

Test an original Fetching Data with API example on Android and iOS with small and large screens, font scaling, dark mode, keyboard and screen reader use, slow/offline networking, denied permissions, and background/foreground transitions. Use DevTools, tests, and a release build where relevant.

Mini challenge

Build it yourself

Test an original Fetching Data with API example on Android and iOS with small and large screens, font scaling, dark mode, keyboard and screen reader use, slow/offline networking, denied permissions, and background/foreground transitions. Use DevTools, tests, and a release build where relevant.

  • Rebuild the example without copying it
  • Test a normal input and an edge case
  • Predict the compiler or output result before running it
javascript
import { useState, useEffect } from 'react';
import { View, Text, ActivityIndicator, FlatList } from 'react-native';

export default function PostsList() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
      .then((data) => setPosts(data))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <ActivityIndicator size="large" />;
  if (error) return <Text>Error: {error}</Text>;

  return (
    <FlatList
      data={posts}
      keyExtractor={(item) => item.id.toString()}
      renderItem={({ item }) => <Text>{item.title}</Text>}
    />
  );
}

Expected: Explain the React and native-platform behavior of Fetching Data with API

Show hint

Test an original Fetching Data with API example on Android and iOS with small and large screens, font scaling, dark mode, keyboard and screen reader use, slow/offline networking, denied permissions, and background/foreground transitions. Use DevTools, tests, and a release build where relevant.

Quick quiz 1 / 3

What best describes the core idea of Fetching Data with API?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • request or permission → native module boundary → result, error, or cleanup
  • Build Fetching Data with API as a lifecycle-aware flow covering permission, loading, empty, offline, timeout, cancellation, retry, foreground/background transitions, and stale data. Clean up subscriptions, timers, and requests.
  • Leaving out useEffect's dependency array ([]) so the API call runs over and over on every render
  • Test an original Fetching Data with API example on Android and iOS with small and large screens, font scaling, dark mode, keyboard and screen reader use, slow/offline networking, denied permissions, and background/foreground transitions. Use DevTools, tests, and a release build where relevant.

React Native Documentation — React Native

Easy traps

  • Leaving out useEffect's dependency array ([]) so the API call runs over and over on every render
  • Running a fetch call without try/catch, so a network error crashes the app
  • Assuming one simulator's happy path proves every real-device, release-build, permission, accessibility, offline, and lifecycle path.

Hands-on Exercise

Test an original Fetching Data with API example on Android and iOS with small and large screens, font scaling, dark mode, keyboard and screen reader use, slow/offline networking, denied permissions, and background/foreground transitions. Use DevTools, tests, and a release build where relevant.

You'll know it worked when: When the app opens, a loading spinner appears, and once the data arrives, the list of post titles is displayed in a FlatList.

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Fetching Data with API | Thuta Learning