Load data from url and show in a flatlist in React Native using hook and async/await

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 :

  1. URI is the url to get the data.

  2. getData is an async function that fetch the data from the given url and returns the json value of it.

  3. ListItem component is used to draw a list item.

  4. 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 :

React Native load data url