Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Loading and Error States | Section
Build a Real App with React Native

bookLoading and Error States

Свайпніть щоб показати меню

Now we want to make the app more realistic.

Fetching data takes time, and sometimes requests fail. If you do not handle these situations, users may see an empty screen and not understand what is happening.

That is why apps usually show:

  • A loading state: while data is being fetched;
  • An error state: if something goes wrong.

Update your HomeScreen.js:

// screens/HomeScreen.js
import { useEffect, useState } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';

export default function HomeScreen({ navigation }) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    async function loadProducts() {
      try {
        const response = await fetch('https://dummyjson.com/products');

        if (!response.ok) {
          throw new Error('Failed to load products');
        }

        const data = await response.json();

        console.log(data.products);
        setItems(data.products.slice(0, 10));
      } catch (err) {
        console.log(err.message);
        setError('Something went wrong while loading products.');
      } finally {
        setLoading(false);
      }
    }

    loadProducts();
  }, []);

  if (loading) {
    console.log('Loading products...');

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

  if (error) {
    console.log(error);

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

  return (
    <View style={styles.container}>
      <Text style={styles.header}>Products</Text>

      {items.map((item) => (
        <Pressable
          key={item.id}
          onPress={() => navigation.navigate('Details', { item })}
          style={styles.item}
        >
          <Text style={styles.itemTitle}>{item.title}</Text>
        </Pressable>
      ))}

      {console.log('Products loaded successfully')}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 20
  },
  header: {
    fontSize: 22,
    fontWeight: 'bold',
    marginBottom: 15
  },
  item: {
    padding: 12,
    backgroundColor: 'lightgray',
    marginBottom: 10,
    borderRadius: 8
  },
  itemTitle: {
    fontSize: 16
  },
  message: {
    fontSize: 16
  },
  error: {
    fontSize: 16,
    color: 'red'
  }
});

Here:

  • loading tracks whether the request is still running;
  • error stores a message if the request fails;
  • try...catch...finally handles success and failure clearly.

This makes the app feel much more complete.

Instead of showing nothing, the app now explains what is happening.

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 5

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 1. Розділ 5
some-alt