Reputation: 636
I'm developing a React Native app.
I'm fetching the data
from RealmDB and grouping by listId
that data.
I want to render below data in FlatList but no data appears.
const data = {
"6": [
{
"id": 13,
"listId": 6,
"piece": 1,
},
{
"id": 12,
"listId": 6,
"piece": 1,
}
],
"7": [
{
"id": 15,
"listId": 7,
"piece": 1,
},
{
"id": 14,
"listId": 7,
"piece": 1,
}
]
}
My attempt was:
<FlatList
numColumns={2}
//keyExtractor={(item) => "key" + item.id}
data={this.state.data}
renderItem={({ item }) => (
<View>
<Text>{item.piece}</Text>
</View>
)}
/>
What is the correct way to use above data
in FlatList
?
Upvotes: 1
Views: 57
Reputation: 16
You can access like this if don't want to change data style.
<FlatList
numColumns={2}
data={this.state.data}
renderItem={({ item }) => (
<View>
<Text>{item[0].piece}</Text>
<Text>{item[1].piece}</Text>
</View>
)}
/>
Upvotes: 0
Reputation: 2565
You can flat your data with that approach:
const flatten = (data) => Object.values(data).flat();
const data = {
"6": [
{
"id": 13,
"listId": 6,
"piece": 1,
},
{
"id": 12,
"listId": 6,
"piece": 1,
}
],
"7": [
{
"id": 15,
"listId": 7,
"piece": 1,
},
{
"id": 14,
"listId": 7,
"piece": 1,
}
]
};
const flatData = flatten(data);
And then you can use it as wanted:
flatData.map(item => item.piece)
Upvotes: 1