Bird
Raised Fist0
React Nativemobile~20 mins

Why API integration connects to backends in React Native - Build It to Prove It

Choose your learning style10 modes available
Build: API Connection Demo
This screen shows how a React Native app connects to a backend using an API to fetch and display data.
Target UI
-------------------------
| API Connection Demo    |
|-----------------------|
| [Fetch Data]          |
|                       |
| Data will appear here |
|                       |
-------------------------
Add a button labeled 'Fetch Data'.
When tapped, fetch data from a public API backend.
Display the fetched data below the button.
Show a loading indicator while fetching.
Handle errors by showing an error message.
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, Button, ActivityIndicator, StyleSheet } from 'react-native';

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

  // TODO: Add function to fetch data from backend API

  return (
    <View style={styles.container}>
      <Text style={styles.title}>API Connection Demo</Text>
      <Button title="Fetch Data" onPress={() => { /* TODO: call fetch function */ }} />
      {loading && <ActivityIndicator size="large" color="#0000ff" />}
      {error && <Text style={styles.error}>{error}</Text>}
      {data && <Text style={styles.data}>{data}</Text>}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, justifyContent: 'center' },
  title: { fontSize: 24, marginBottom: 20, textAlign: 'center' },
  data: { marginTop: 20, fontSize: 16, textAlign: 'center' },
  error: { marginTop: 20, fontSize: 16, color: 'red', textAlign: 'center' }
});
Task 1
Task 2
Task 3
Solution
React Native
import React, { useState } from 'react';
import { View, Text, Button, ActivityIndicator, StyleSheet } from 'react-native';

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

  async function fetchData() {
    setLoading(true);
    setError(null);
    setData(null);
    try {
      const response = await fetch('https://api.chucknorris.io/jokes/random');
      if (!response.ok) throw new Error('Network response was not ok');
      const json = await response.json();
      setData(json.value);
    } catch (e) {
      setError('Failed to fetch data.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>API Connection Demo</Text>
      <Button title="Fetch Data" onPress={fetchData} />
      {loading && <ActivityIndicator size="large" color="#0000ff" />}
      {error && <Text style={styles.error}>{error}</Text>}
      {data && <Text style={styles.data}>{data}</Text>}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, justifyContent: 'center' },
  title: { fontSize: 24, marginBottom: 20, textAlign: 'center' },
  data: { marginTop: 20, fontSize: 16, textAlign: 'center' },
  error: { marginTop: 20, fontSize: 16, color: 'red', textAlign: 'center' }
});

This React Native screen demonstrates why API integration connects to backends. When the user taps the 'Fetch Data' button, the app calls a backend API (a public joke API) to get data. The app shows a loading spinner while waiting. If the fetch succeeds, it displays the joke text. If it fails, it shows an error message.

This shows how the app talks to a backend server through an API to get fresh data, which is a common pattern in mobile apps.

Final Result
Completed Screen
-------------------------
| API Connection Demo    |
|-----------------------|
| [Fetch Data]          |
|                       |
| Chuck Norris joke text |
|                       |
-------------------------
User taps 'Fetch Data' button.
Loading spinner appears while fetching.
Fetched joke text appears below the button.
If network fails, an error message appears instead.
Stretch Goal
Add a refresh button to fetch new data without restarting the app.
💡 Hint
Reuse the fetchData function and add a small refresh icon button next to the 'Fetch Data' button.

Practice

(1/5)
1. Why does a React Native app use API integration to connect to a backend server?
easy
A. To get or send data between the app and the server
B. To change the app's color scheme automatically
C. To increase the app's font size on the screen
D. To store data only on the user's device

Solution

  1. Step 1: Understand the role of backend servers

    Backend servers store and manage data that apps need to access or update.
  2. Step 2: Recognize API integration purpose

    API integration allows the app to communicate with the backend to get or send this data.
  3. Final Answer:

    To get or send data between the app and the server -> Option A
  4. Quick Check:

    API integration connects app and backend data [OK]
Hint: API integration moves data between app and server [OK]
Common Mistakes:
  • Thinking API changes app design automatically
  • Confusing local storage with backend data
  • Believing API only changes UI elements
2. Which of the following is the correct way to fetch data from an API in React Native using async/await?
easy
A. const data = fetch('https://api.example.com/data').json();
B. const response = await fetch('https://api.example.com/data'); const data = await response.json();
C. fetch('https://api.example.com/data').then(response => response.text());
D. await fetch('https://api.example.com/data').json();

Solution

  1. Step 1: Use fetch with await to get response

    fetch returns a promise; await waits for it to resolve to a response object.
  2. Step 2: Use await on response.json() to parse JSON data

    response.json() returns a promise that resolves to the parsed data.
  3. Final Answer:

    const response = await fetch('https://api.example.com/data'); const data = await response.json(); -> Option B
  4. Quick Check:

    Use await twice: fetch and json() [OK]
Hint: Await fetch, then await response.json() [OK]
Common Mistakes:
  • Calling json() directly on fetch without await
  • Using response.text() instead of response.json()
  • Missing await keyword causing unresolved promises
3. What will be logged to the console after this React Native code runs?
async function getData() {
  const response = await fetch('https://api.example.com/user');
  const user = await response.json();
  console.log(user.name);
}
getData();
medium
A. The entire user object printed as a string
B. undefined
C. An error because fetch is not awaited
D. The user's name from the API response

Solution

  1. Step 1: Await fetch and parse JSON

    The code waits for the fetch call and parses the JSON response into the user object.
  2. Step 2: Log the user's name property

    console.log prints the value of user.name from the parsed object.
  3. Final Answer:

    The user's name from the API response -> Option D
  4. Quick Check:

    Await fetch and json() gives user.name [OK]
Hint: Await fetch and json() before accessing data [OK]
Common Mistakes:
  • Forgetting await causing unresolved promises
  • Logging user instead of user.name
  • Assuming fetch returns data directly without parsing
4. Identify the error in this React Native API call code:
async function fetchData() {
  const response = fetch('https://api.example.com/data');
  const data = await response.json();
  console.log(data);
}
medium
A. Using await on response.json() is incorrect
B. fetch URL is invalid syntax
C. Missing await before fetch causing response to be a promise
D. console.log should be inside a .then() block

Solution

  1. Step 1: Check fetch call usage

    fetch returns a promise, so it must be awaited to get the response object.
  2. Step 2: Identify consequence of missing await

    Without await, response is a promise, so calling response.json() causes an error.
  3. Final Answer:

    Missing await before fetch causing response to be a promise -> Option C
  4. Quick Check:

    Always await fetch before response.json() [OK]
Hint: Await fetch before calling response.json() [OK]
Common Mistakes:
  • Assuming fetch returns data immediately
  • Calling json() on a promise instead of response
  • Misunderstanding async/await order
5. You want your React Native app to show updated weather data every time the user opens the app. Which approach best uses API integration to achieve this?
hard
A. Call the weather API inside a useEffect hook that runs on component mount
B. Store weather data once in a variable and never update it
C. Fetch weather data only when the user presses a button
D. Hardcode weather data in the app code

Solution

  1. Step 1: Understand when to fetch updated data

    To get fresh data each time the app opens, fetch on component mount is ideal.
  2. Step 2: Use React Native lifecycle with useEffect

    useEffect with empty dependency array runs once on mount, perfect for initial API call.
  3. Final Answer:

    Call the weather API inside a useEffect hook that runs on component mount -> Option A
  4. Quick Check:

    useEffect on mount fetches fresh data [OK]
Hint: Fetch data on mount with useEffect [OK]
Common Mistakes:
  • Not updating data after first load
  • Fetching only on user action missing auto updates
  • Hardcoding data prevents real-time updates
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