Anees Ahmad
Anees Ahmad

Reputation: 3

Manipulate SectionList from API

I am fetching and manipulating my sectionList by api data. My api events list looks like this.

{
    "events": [
        {
            "event_id": 76,
            "core_symptom": "tiredness",
            "note": "Tiredness after short walk",
            "created_at": "2020-06-29T03:09:24.000Z",
            "audio_url": "https://medbeat.beat.se",
            "audio_title": "2020-02-20 11:57:22",
            "monitor_id": 2
        },     
        {
            "event_id": 68,
            "core_symptom": "headpain",
            "note": "Head pain test entry from mobile phone",
            "created_at": "2020-06-24T03:35:54.000Z",
            "audio_url": "https://medbeat.beat.se",
            "audio_title": "2020-02-20 11:57:22",
            "monitor_id": 2
        },
    ]
}

please help me how can I use "created_at" as section header and "core_symptom" as list items.

Upvotes: 0

Views: 357

Answers (1)

Fabrizio Rizzonelli
Fabrizio Rizzonelli

Reputation: 429

Expected data structure for SectionList is an array of "sections" (you can check more here). What I usually do when working with them is using some third party library like lodash, i.e. the groupBy function.

import { groupBy, map } from 'lodash'

const dictionary = groupBy(yourEventAPIArray, e => e.created_at;

const sections = map(dictionary, (data, key) => {
   day: key,
   data
});

Now you have a proper structure for sections props of SectionList, you just need to pass it and work with renderItem and renderSectionHeader.

<SectionList sections={sections} 
  renderItem={({ item, index }) => <Text>{item.core_symptom}</Text>}  
  renderSectionHeader={({ section }) => <Text>{section.day}</Text>}
/>

As you can see, basically sections is just an array with a prop for key (you section header) and a data which is the array of items for that sections.

Hope it'll help :)

Upvotes: 1

Related Questions