Home > Mobile >  I am trying to populate a simple list from an API Call, I can log the data but when I try to display
I am trying to populate a simple list from an API Call, I can log the data but when I try to display

Time:04-14

pretty new to react-native I am trying to fetch data to create a flat list based on the array I am populating from the data. I am able to fetch the data and log it, but when I try to display it on flatlist the data is not showing and I do not get any errors or anything. When I try to access one of the items of the array I am getting undefined. Very confused as to why its not working.

import React, {useState, useEffect} from 'react'
import { StyleSheet, Text, View, Button, FlatList, ActivityIndicator, SafeAreaViewView } from 'react-native';

export default function WorkOrderList() {
    const [isLoading, setIsLoading] = useState(false);
    const [data, setData] = useState([]);
    const [error, setError] = useState(null);


    const API_ENDPOINT = 'https://randomuser.me/api/?seed=1&page=1&results=20';



    useEffect(()=>{
        setIsLoading(true);

        fetch(API_ENDPOINT)
        .then((response) => response.json())
        .then(results => {
            setData(results);
            setIsLoading(false);
            console.log(data)
        })
        .catch(err => {
            setIsLoading(false);
            setError(err);
            console.log(err)
        })
    },[]);

    if (isLoading) {
        return(      
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" color="#5500dc" />
      </View>
      )
    }
    if (error) {
        return (
          <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <Text style={{ fontSize: 18}}>
              Error fetching data... Check your network connection!
              {JSON.stringify(error)}
            </Text>
          </View>
        );
      }
      return (
        <View  style={styles.container}>
          <Text style={styles.text}>Favorite Contacts</Text>
          <FlatList
            data={data}
            keyExtractor={item => item.first}
            renderItem={item => (
              <View style={styles.listItem}>
                <Image
                  source={{ uri:item.picture.thumbnail}}
                  style={styles.coverImage}
                />
                <View style={styles.metaInfo}>
                  <Text style={styles.title}>{`${item.name.first} ${
                    item.name.last
                  }`}</Text>
                </View>
              </View>
            )}
          />
        </View >
      );

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f8f8',
    alignItems: 'center'
  },
  text: {
    fontSize: 20,
    color: '#101010',
    marginTop: 60,
    fontWeight: '700'
  },
  listItem: {
    marginTop: 10,
    paddingVertical: 20,
    paddingHorizontal: 20,
    backgroundColor: '#fff',
    flexDirection: 'row'
  },
  coverImage: {
    width: 100,
    height: 100,
    borderRadius: 8
  },
  metaInfo: {
    marginLeft: 10
  },
  title: {
    fontSize: 18,
    width: 200,
    padding: 10
  }
});

Image of terminal

CodePudding user response:

  1. FlatList data Props should be the type of Array.

you need to update the setData to,

   fetch(API_ENDPOINT)
        .then((response) => response.json())
        .then(results => {
            setData(results.results); // <-- from the API data is in results object
    ...

  1. After the data state is correct update the UI for FlatList as,
<FlatList
  data={data}
  keyExtractor={item => item.first}
  renderItem={({ item }) => (
    <View style={styles.listItem}>
      <Image
        source={{ uri:item.picture.thumbnail}}
        style={styles.coverImage}
      />
      <View style={styles.metaInfo}>
        <Text style={styles.title}>{`${item.name.first} ${
          item.name.last
        }`}</Text>
      </View>
    </View>
  )}
/>

For more details on FlatList component - https://reactnative.dev/docs/flatlist

  • Related