This app shows a button to load data. When pressed, it shows a spinner for 2 seconds. Then it randomly shows data or an error message.
import React from 'react';
import { View, Text, Button, ActivityIndicator } from 'react-native';
export default function LoadingErrorExample() {
const [loading, setLoading] = React.useState(false);
const [error, setError] = React.useState(null);
const [data, setData] = React.useState(null);
const fetchData = () => {
setLoading(true);
setError(null);
setData(null);
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
setData('Here is your data!');
setLoading(false);
} else {
setError('Failed to load data.');
setLoading(false);
}
}, 2000);
};
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
{loading && <ActivityIndicator size="large" color="#0000ff" />}
{error && <Text style={{ color: 'red', marginBottom: 10 }}>{error}</Text>}
{data && <Text style={{ marginBottom: 10 }}>{data}</Text>}
{!loading && !data && !error && <Text>Press the button to load data.</Text>}
<Button title="Load Data" onPress={fetchData} />
</View>
);
}