I am new to react and am trying to build a simple app however am having trouble accessing objects within objects.
I have tried to replace the FlatList with a VirtualizedList like the documentation suggests when the data is not a plain array, however this also did not work. Is there a proper way of tackling this issue or do I just have to get creative with how I format my data?
Code:
const Owe = ({navigation, route}) => {
return (
<SafeAreaView>
<FlatList
data={information}
renderItem={({item}) =>
<View style={flatListStyle.container}>
<Text style={titleBar.Text}>{route.data.message}</Text>
</View>}
/>
</SafeAreaView>
);
}
var information = [
{nme:"Joe", data: [
{owed:true, amount: 10, message:"Beer Money"},
{owed:false,amount: 5, message:"Lunch"}
]},
{nme:"Ben", data:[
{owed:true, amount: 50, message:"Broke bitch"},
{owed:false, amount: 12.50, message:"Milk"}
]}
];
Error message: "undefined is not an object (evaluating route.data.message)"
CodePudding user response:
something is wrong with your code, didn't get this code tbh route.data.message I guess it's item.message and since it's array maybe should looks like
<View style={flatListStyle.container}>
<Text>{item.nme}</Text>
{/* show all message */}
{item.data.map((message, index) => <Text key={index} style={titleBar.Text}>{message}</Text>}
</View>}
CodePudding user response:
route is not related to your information array, if you want to access item.data.message, then you have to iterate over item.data, because in information array, data is an array.
Here is your working code
import { SafeAreaView, FlatList, View, Text } from 'react-native';
const Owe = ({ navigation, route }) => {
return (
<SafeAreaView>
<FlatList
data={information}
renderItem={({ item }) => (
<View style={flatListStyle.container}>
<Text style={[titleBar.Text,{fontWeight: 'bold' }]}>
{item.nme}
</Text>
{item.data.map((dataItem) => (
<Text style={{ color: 'black' }}>{dataItem.message}</Text>
))}
</View>
)}
/>
</SafeAreaView>
);
};
var information = [
{
nme: 'Joe',
data: [
{ owed: true, amount: 10, message: 'Beer Money' },
{ owed: false, amount: 5, message: 'Lunch' },
],
},
{
nme: 'Ben',
data: [
{ owed: true, amount: 50, message: 'Broke bitch' },
{ owed: false, amount: 12.5, message: 'Milk' },
],
},
];
export default Owe;