Reputation: 101
I've been pulling data from my rails API to render in a list of already made contacts. I've been able to render the contact data easily enough on a FlatList, but now I want to order and display the data in an alphabetical SectionList depending on the first letter of the contact name.
I have managed to get rails to give me the JSON correctly (?). But getting stuck rendering the section list. I'm not sure if I need to restructure the JSON response or if I'm missing something simple in renderSectionHeader
This is the JSON:
contacts: {
data: {
J: [
{
id: 1,
email: '[email protected]',
password_digest: '-',
phone_number: '+1',
name: 'Jay',
circle_id: 'Jay',
bio: null,
created_at: '2020-07-17T11:05:47.479Z',
updated_at: '2020-07-17T20:22:25.821Z'
}
],
K: [
{
id: 1,
email: '[email protected]',
password_digest: '-',
phone_number: '+2',
name: 'Kay',
circle_id: 'Kay',
bio: null,
created_at: '2020-07-17T11:05:48.479Z',
updated_at: '2020-07-17T20:22:28.821Z'
}
]
This is the SectionList:
<SectionList style={{width: '100%', marginTop: 10 }}
sections={this.props.contacts.data}
renderItem={({item}) =>
<TouchableOpacity>
<ContactBasic item={item}/>
</TouchableOpacity>}
renderSectionHeader={({section}) => (
<Text style={styles.sectionHeader}>{section.data}</Text>)}
keyExtractor={(item, index) => index}
ListEmptyComponent={() => (
<View>
<Button title="No Contacts Found" type="clear"/>
</View>
)}
/>
This is the ContactBasic Component:
<View style={styles.contactContainer}>
<View style={styles.contact}>
<Image style={styles.image}/>
<View style={styles.contactText}>
<Text style={styles.contactName}>{props.item.name}</Text>
</View>
</View>
</View>
Upvotes: 2
Views: 1799
Reputation: 16334
Your json structure is not compatible you have an object as data not an array
data: {
J: [
{}
}
You will have to convert it to a structure like below
data: [
{title:'J',contacts:[]}
]
When section list calls the reduce function in the array it throws the error. If you can handle this on the api level it would be easy, otherwise you will have to do this at JS level.
Upvotes: 4