React native load data over the network :
In this tutorial, I will show you how we can fetch data from a URL and load it into a FlatList in react native. We will use async/await to load the data and using react hook, we will populate it in a list.
For this example, we are using jsonplaceholder api to get a list of dummy objects.
React native program :
The below react-native program illustrates how to do it :
import React, {useState} from 'react';
import {StyleSheet, View, Text, FlatList, SafeAreaView} from 'react-native';
const URI = 'https://jsonplaceholder.typicode.com/todos/';
const getData = async () => {
try {
let response = await fetch(URI);
let json = await response.json();
return json;
} catch (error) {
console.error(error);
}
};
const ListItem = ({item}) => {
return (
<View style={styles.listItem}>
<Text style={styles.listText}>{item.title}</Text>
</View>
);
};
const App = () => {
const [items, setItems] = useState([]);
getData().then(items => setItems(items));
return (
<SafeAreaView style={styles.parentView}>
<FlatList
style={styles.flatList}
data={items}
keyExtractor={item => item.id.toString()}
renderItem={({item}) => <ListItem item={item} />}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
parentView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop: 22,
},
flatList: {
width: '100%',
},
listText: {
color: 'white',
},
listItem: {
flex: 1,
marginRight: 20,
marginLeft: 20,
marginTop: 10,
backgroundColor: '#776677',
padding: 10,
borderRadius: 5,
},
});
export default App;
Explanation :
-
URI is the url to get the data.
-
getData is an async function that fetch the data from the given url and returns the json value of it.
-
ListItem component is used to draw a list item.
-
Inside App component, we are using one FlatList to show the items. We are calling the async function to load the data and once it is loaded, we are assigning the values to items. This will change the state and reload the FlatList.
Output :
This program will give the below output :