import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';
import axios from 'axios';
export default function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
setUsers(response.data);
setLoading(false);
})
.catch(() => {
setError('Failed to load users');
setLoading(false);
});
}, []);
if (loading) {
return (
<View style={styles.container}>
<Text>Loading...</Text>
</View>
);
}
if (error) {
return (
<View style={styles.container}>
<Text style={styles.error}>{error}</Text>
</View>
);
}
return (
<View style={styles.container}>
<FlatList
data={users}
keyExtractor={item => item.id.toString()}
renderItem={({ item }) => <Text style={styles.item}>{item.name}</Text>}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#fff'
},
item: {
fontSize: 18,
paddingVertical: 10
},
error: {
color: 'red',
fontSize: 16
}
});This solution uses the Axios library to fetch user data from a public API when the component loads.
We use useEffect to run the fetch once after the screen appears.
While loading, it shows a simple 'Loading...' text.
If there is an error fetching data, it shows a red error message.
When data is loaded successfully, it displays the user names in a scrollable list using FlatList.
This approach keeps the UI responsive and handles errors gracefully.