Search code examples
react-nativefetchreact-native-flatlistflatlist

React Native FlatList only rendering 1 object


I know that the answer is probably simple, but I'm currently learning and I do not understand why my flatlist is only grabbing the first object in the array. Help would be very appriciated.

import { FlatList, Text, SafeAreaView, View, StyleSheet, Image, Button, } from 'react-native';
import { useEffect, useState } from 'react';

const API =
    'https://api.punkapi.com/v2/beers';

const renderDrinks = ({ item }) => (
    <Drinks
        id={item.id}
        name={item.name}
        desc={item.description}
        img={item.image_url}
        abv={item.abv}
    />
);

const Drinks = (props) => (
    <View style={styles.item}>
        <Text style={styles.itemText}>Id: {props.id}</Text>
        <Text style={styles.itemText}>Name: {props.name}</Text>
        <Text style={styles.itemText}>ABV: {props.abv}%</Text>
        <Text style={styles.itemText}>Description: {props.desc}</Text>
        <Image source={{uri: props.img}}/>
    </View>
);

export default function App() {
    const [data, setData] = useState([]);
    const [refresh, onRefresh] = useState(false)
    useEffect(() => {
        fetch(API)
            .then((response) => response.json())
            .then(([data]) => {
                setData(data);
            });
    }, [refresh]);

    return (
        <SafeAreaView style={styles.container}>
            <Button style={styles.button} onPress={() => onRefresh(!refresh)} title="Refresh" />
            <FlatList
                style={styles.drinkList}
                data={[data]}
                renderItem={renderDrinks}
            />
        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    drinkList: { alignContent: 'stretch', width: '100%' },
    container: {
        flex: 1,
        justifyContent: 'center',
        paddingTop: 40,
        backgroundColor: '#222222',
        padding: 8,
    },
    item: {
        borderWidth: 1,
        borderColor: 'white',
        padding: 13,
        margin: 7,
        borderRadius: 7,
        backgroundColor: 'green',
    },
    itemText: { color: 'white' },
});

Also, if someone knows how to get the image to appear, that would be awesome. Thank you!


Solution

  • if trying to destructuring property from an object you should use { data } not [data]

    here you should for example do that in useEffect
    useEffect(() => { fetch(API) .then((response) => response.json()) .then((response) => { setData(response); }); }, [refresh]);

    and change Flatlist to <FlatList style={styles.drinkList} data={data} renderItem={renderDrinks} />