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.