Bird
Raised Fist0
React Nativemobile~20 mins

Loading and error states in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Data Fetch Screen
This screen fetches data from a fake API and shows loading and error states.
Target UI
-------------------------
| Data Fetch Screen      |
|-----------------------|
| [Loading spinner]      |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
-------------------------
Show a loading spinner while fetching data
Show fetched data as text when successful
Show an error message if fetching fails
Add a button to retry fetching data
Starter Code
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, ActivityIndicator, StyleSheet } from 'react-native';

export default function DataFetchScreen() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState(null);

  // TODO: Add fetchData function here

  useEffect(() => {
    // TODO: Call fetchData when component mounts
  }, []);

  return (
    <View style={styles.container}>
      {/* TODO: Show loading spinner, data text, or error message here */}
      {/* TODO: Add retry button here */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  }
});
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Solution
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, ActivityIndicator, StyleSheet } from 'react-native';

export default function DataFetchScreen() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState(null);

  async function fetchData() {
    setLoading(true);
    setError(null);
    setData(null);
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
      if (!response.ok) throw new Error('Network response was not ok');
      const json = await response.json();
      setData(json);
    } catch (e) {
      setError('Failed to load data.');
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <View style={styles.container}>
      {loading && <ActivityIndicator size="large" color="#0000ff" accessibilityLabel="Loading indicator" />}
      {!loading && error && <Text accessibilityRole="alert" style={styles.errorText}>{error}</Text>}
      {!loading && data && <Text style={styles.dataText}>{data.title}</Text>}
      <Button title="Retry" onPress={fetchData} accessibilityLabel="Retry fetching data button" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  },
  errorText: {
    color: 'red',
    marginBottom: 12,
    fontSize: 16
  },
  dataText: {
    fontSize: 18,
    marginBottom: 12
  }
});

This screen uses React Native hooks to manage loading, error, and data states.

The fetchData function is async. It sets loading to true and clears previous error and data. Then it fetches data from a fake API. If successful, it saves the data. If there is an error, it sets an error message. Finally, it sets loading to false.

The useEffect hook calls fetchData once when the screen loads.

The UI shows a spinner while loading, an error message if there was a problem, or the fetched data's title if successful. The Retry button lets the user try fetching again.

Accessibility labels and roles help screen readers understand the UI states.

Final Result
Completed Screen
-------------------------
| Data Fetch Screen      |
|-----------------------|
|       (spinner)        |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
| [Retry Button]         |
-------------------------
When the screen loads, a spinner appears while data loads.
If loading succeeds, the data title text appears.
If loading fails, an error message appears in red.
Pressing the Retry button tries to fetch data again.
Stretch Goal
Add pull-to-refresh functionality to reload data when the user swipes down.
💡 Hint
Use React Native's RefreshControl with a ScrollView or FlatList to implement pull-to-refresh.

Practice

(1/5)
1. What is the main purpose of a loading state in a React Native app?
easy
A. To display an error message when something goes wrong
B. To show the user that data is being fetched or processed
C. To permanently hide content from the user
D. To restart the app automatically

Solution

  1. Step 1: Understand loading state role

    Loading states inform users that the app is busy fetching or processing data.
  2. Step 2: Differentiate from error state

    Error states show problems, not loading progress.
  3. Final Answer:

    To show the user that data is being fetched or processed -> Option B
  4. Quick Check:

    Loading state = show progress [OK]
Hint: Loading means waiting for data, not errors [OK]
Common Mistakes:
  • Confusing loading with error states
  • Thinking loading hides content permanently
  • Assuming loading restarts the app
2. Which of the following is the correct way to declare a loading state using React Native's useState hook?
easy
A. const loading = useState(false);
B. let loading = useState(true);
C. var loading = useState(false);
D. const [loading, setLoading] = useState(false);

Solution

  1. Step 1: Recall useState syntax

    useState returns an array with current value and setter function, usually destructured.
  2. Step 2: Check options for correct destructuring

    const [loading, setLoading] = useState(false); correctly uses array destructuring with const and initial value false.
  3. Final Answer:

    const [loading, setLoading] = useState(false); -> Option D
  4. Quick Check:

    useState destructuring = const [loading, setLoading] = useState(false); [OK]
Hint: useState returns [value, setter], destructure with const [a,b] [OK]
Common Mistakes:
  • Not destructuring the array from useState
  • Using let or var instead of const
  • Assigning useState directly to a variable without destructuring
3. Given this React Native snippet, what will be displayed when loading is true?
const [loading, setLoading] = useState(true);
return (
  loading ? Loading... : Data loaded
);
medium
A. Loading...
B. Nothing is displayed
C. Data loaded
D. Error message

Solution

  1. Step 1: Check the value of loading

    loading is true initially.
  2. Step 2: Evaluate the ternary expression

    If loading is true, Loading... is returned and shown.
  3. Final Answer:

    Loading... -> Option A
  4. Quick Check:

    loading true shows loading text [OK]
Hint: Ternary shows first option if condition true [OK]
Common Mistakes:
  • Confusing true and false branches
  • Thinking nothing shows when loading is true
  • Assuming error message shows automatically
4. Identify the error in this React Native code handling loading and error states:
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);

if (loading) {
  return Loading...;
} else if (error) {
  return Error occurred;
}
return Data loaded;
medium
A. Error state should be a boolean, not null
B. The if-else logic is reversed
C. Loading state should be true initially to show loading
D. No error, code works fine

Solution

  1. Step 1: Check initial loading state

    Loading is false initially, so loading screen never shows on start.
  2. Step 2: Understand typical loading flow

    Loading should start as true while fetching data, then false after.
  3. Final Answer:

    Loading state should be true initially to show loading -> Option C
  4. Quick Check:

    Initial loading true needed to show loading [OK]
Hint: Loading usually starts true before data fetch [OK]
Common Mistakes:
  • Setting loading false initially hides loading screen
  • Thinking error must be boolean
  • Assuming if-else order is wrong
5. You want to show a loading spinner while fetching data, then show an error message if fetch fails, or the data if successful. Which React Native pattern correctly handles these states?
hard
A. Use separate states: loading (boolean), error (string|null), data (object|null), and conditionally render based on these
B. Only use a loading state and ignore errors
C. Use a single state variable for all three states with strings 'loading', 'error', 'data'
D. Render data immediately without any loading or error checks

Solution

  1. Step 1: Understand state separation

    Separate states for loading, error, and data allow clear control of UI for each condition.
  2. Step 2: Evaluate options

    Use separate states: loading (boolean), error (string|null), data (object|null), and conditionally render based on these uses best practice: boolean loading, error message or null, and data object or null.
  3. Final Answer:

    Use separate states: loading (boolean), error (string|null), data (object|null), and conditionally render based on these -> Option A
  4. Quick Check:

    Separate states for clarity and control [OK]
Hint: Use separate states for loading, error, and data [OK]
Common Mistakes:
  • Ignoring error handling
  • Using one string state for all conditions
  • Rendering data without waiting for fetch
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard