Home > database >  I can't display the data from an API into a FlatList, but I see it in my console.log. What is t
I can't display the data from an API into a FlatList, but I see it in my console.log. What is t

Time:12-22

Console logging my react native app shows the data I fetch from an API. The problem now is that it is not displaying in the FlatList.

const HealthLinkMain = () => {
    const [data, setData] = useState([]);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await axios.get(API_URL, {
                    method: "GET",
                    headers: {
                        Authorization: `Bearer ${TOKEN}`,
                    },
                });
                setData(response.data)
            } catch (error) {
                console.error(error);
            }
        };

        fetchData();
    }, []);
    return (
        <View style={styles.container}>
            <Text>Test</Text>
            <FlatList
                data={data.data}
                renderItem={(item) => (
                    <View>
                        <Text>{item.clinic_name}</Text>
                        <Text>{item.clinic_address}</Text>
                    </View>
                )}
                keyExtractor={(item, index) => item.clinic_name}
            />
        </View>
    );
};

CodePudding user response:

I think the problem might be in your renderItem as you haven't destructured the item, try this:

renderItem={({item}) => (
                <View>
                    <Text>{item.clinic_name}</Text>
                    <Text>{item.clinic_address}</Text>
                </View>
            )}

You can also seperate it the renderItem into a function of it's own which a lot of people tend to do:

const renderItem = ({item}) => {
     return(
            <View>
                <Text>{item.clinic_name}</Text>
                <Text>{item.clinic_address}</Text>
            </View>
     )
}

and then change the flatlist calling function accordingly:

            <FlatList
                data={data.data}
                renderItem={renderItem}
                keyExtractor={(item, index) => item.clinic_name}
            />
  • Related