Loading and Error States
Veeg om het menu te tonen
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:
loadingtracks whether the request is still running;errorstores a message if the request fails;try...catch...finallyhandles success and failure clearly.
This makes the app feel much more complete.
Instead of showing nothing, the app now explains what is happening.
Was alles duidelijk?
Bedankt voor je feedback!
Sectie 1. Hoofdstuk 5
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Sectie 1. Hoofdstuk 5