Reputation: 907
I need to render a FlatList
after fetching a json containing connections
. The following piece of code runs correctly but the travel
object inside the renderItem
is always undefined
.
import {Text, View, FlatList, ActivityIndicator} from 'react-native';
import React, {useEffect, useState} from 'react';
/**
* http://transport.opendata.ch/v1/connections?from=8575201&to=8503000
*/
export function TravelsScreen({navigation}) {
const [isLoading, setLoading] = useState(true);
const [travels, setTravels] = useState([]);
useEffect(() => {
fetch('http://transport.opendata.ch/v1/connections?from=8575201&to=8503000')
.then(response => response.json())
.then(json => setTravels(json.connections))
.catch(error => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<View style={{flex: 1, padding: 24}}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={travels}
renderItem={({travel}) => <Text>Travel: {console.log(travel)}</Text>}
keyExtractor={travel => travel.from.departureTimestamp.toString()}
/>
)}
</View>
);
}
Upvotes: 1
Views: 165
Reputation: 11932
Please update your FlatList to :
<FlatList
data={travels}
renderItem={({item}) => {console.log(item)}}
//other properties
/>
From official documentation the renderItem
method takes out item
from the FlatList array and since you are using the destructuring
syntax to extract it, you should explicitly use item
. An alternative without the destructuring
syntax would look like :
<FlatList
data={travels}
renderItem={(travel) =>{ console.log(travel.item)}}
//other properties
/>
Upvotes: 1