0
0
React Nativemobile~20 mins

Fetch API for GET requests in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: User List
This screen fetches a list of users from a public API and displays their names in a scrollable list.
Target UI
-------------------------
|       User List        |
-------------------------
| Loading...             |
|                       |
|                       |
|                       |
|                       |
-------------------------
Fetch user data from https://jsonplaceholder.typicode.com/users using GET request
Show a loading text while fetching data
Display the list of user names in a scrollable list after data is loaded
Handle errors by showing an error message
Starter Code
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';

export default function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // TODO: Add fetch code here
  }, []);

  return (
    <View style={styles.container}>
      {/* TODO: Add UI rendering code here */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff'
  },
  itemText: {
    fontSize: 18,
    paddingVertical: 10
  },
  errorText: {
    color: 'red',
    fontSize: 16
  }
});
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Task 7
Task 8
Solution
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';

export default function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then(data => {
        setUsers(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return (
      <View style={styles.container}>
        <Text>Loading...</Text>
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.container}>
        <Text style={styles.errorText}>Error: {error}</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <FlatList
        data={users}
        keyExtractor={item => item.id.toString()}
        renderItem={({ item }) => <Text style={styles.itemText}>{item.name}</Text>}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff'
  },
  itemText: {
    fontSize: 18,
    paddingVertical: 10
  },
  errorText: {
    color: 'red',
    fontSize: 16
  }
});

This React Native component uses the fetch API to get user data from a public URL. We start by setting loading to true and error to null. Inside useEffect, we call fetch with the URL. We check if the response is okay, then parse it as JSON. The data is saved in the users state, and loading is set to false.

If there is an error during fetching, we catch it and save the error message, also stopping the loading state.

In the UI, if loading is true, we show a simple loading text. If there is an error, we show the error message in red. Otherwise, we display the list of user names using FlatList, which is scrollable and efficient for lists.

This approach keeps the UI responsive and informs the user about the current state (loading, error, or data shown).

Final Result
Completed Screen
-------------------------
|       User List        |
-------------------------
| Leanne Graham          |
| Ervin Howell           |
| Clementine Bauch       |
| Patricia Lebsack       |
| Chelsey Dietrich       |
| Mrs. Dennis Schulist   |
| Kurtis Weissnat        |
| Nicholas Runolfsdottir |
| Glenna Reichert        |
| Clementina DuBuque     |
-------------------------
When the screen loads, it shows 'Loading...' text.
After data is fetched, the list of user names appears.
User can scroll the list vertically to see all names.
If network fails, an error message is shown instead.
Stretch Goal
Add a pull-to-refresh feature to reload the user list when the user swipes down.
💡 Hint
Use FlatList's refreshing and onRefresh props to implement pull-to-refresh.