0
0
React Nativemobile~20 mins

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

Choose your learning style9 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.