Ethan Yan
Ethan Yan

Reputation: 121

how to create dynamic data source for sectionlist in RN?

I am currently using sectionlist to create a list with a header, but I am struggling with dataSource.

Object {
   "A": Array [
     Object {
       "fid": "2",
       "name": "Manage",
       "posts": "1",
       "threads": "1",
       "todayposts": "1",
     },
   ],
   "B": Array [
     Object {
       "fid": "36",
       "name": "Anime",
       "posts": "1",
       "threads": "1",
       "todayposts": "1",
     },
     Object {
       "fid": "37",
       "name": "Novel",
       "posts": "2",
       "threads": "2",
      "todayposts": "2",
     },
  ],
}

these are the data fetched from the server, and they are objects, so right now I have to transfer these data to a struct which can be accepted by section list, otherwise, I got an error message like,

TypeError:props.section.reduce is not a function.(In 'props.sections.reduce(function(v,section){
      stickyHeaderIndices.push(v+offset);
      return v + section.data.length +2;
},0)','props.sections.reduce' is undefined)

So what I tried is, using for loop to create a new array, but seems I failed.

Update:

<SectionList
sections={dataSource}

/>

So clearly I need a dataSource is an array with keys inside, not the one I have right now. So I need to find a way to trans the current object to array.

Can anyone help me with this?

Upvotes: 2

Views: 2583

Answers (1)

Ethan Yan
Ethan Yan

Reputation: 121

So I figured out how to change it from object to an array with keys.

let SECTIONS = []
      for (const key in dataSource) {
          if (dataSource.hasOwnProperty(key)) {
              SECTIONS.push({
                  data: dataSource[key],
                  key: key,
              })
          }
}

It solved my problem.

Upvotes: 1

Related Questions