0
0
React Nativemobile~20 mins

JSON response parsing in React Native - Mini App: Build & Ship

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

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

  useEffect(() => {
    // TODO: Fetch JSON data and update state
  }, []);

  return (
    <View style={styles.container}>
      {/* TODO: Show loading, error or user list here */}
    </View>
  );
}

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

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

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => {
        setUsers(data);
        setLoading(false);
      })
      .catch(err => {
        setError('Failed to load users');
        setLoading(false);
      });
  }, []);

  if (loading) {
    return (
      <View style={styles.container}>
        <ActivityIndicator size="large" color="#0000ff" />
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.container}>
        <Text style={styles.errorText}>{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: 16,
    backgroundColor: '#fff'
  },
  itemText: {
    fontSize: 18,
    paddingVertical: 8
  },
  errorText: {
    color: 'red',
    fontSize: 16
  }
});

This solution uses React Native hooks to manage state and side effects.

We start with three states: users for the list, loading to show a spinner, and error to show any problems.

Inside useEffect, we fetch the JSON from the API. When the data arrives, we save it in users and stop loading. If there is an error, we save an error message and stop loading.

The UI shows a spinner while loading, an error message if there is an error, or the list of user names when data is ready.

Using FlatList makes the list scrollable and efficient.

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, a spinner appears while fetching data.
After data loads, the spinner disappears and the list of user names appears.
User can scroll vertically through the list.
If fetching 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.