Jonathan Reis
Jonathan Reis

Reputation: 47

How to list two different data in the same FlatList?

I would just like to use a FlatList to list annotation and editedAnnotation, but I can't list both. As shown below, it is listing annotation only.

My state and API:

const [cards, setCards] = useState([]);
useEffect(() => {
  async function loadCards() {
      const response = await api.get('annotation');
      setCards(response.data);
  }
  loadCards();
}, []);

My list:

<FlatList
  data={cards.Annotation}
  keyExtractor={call => String(call.id)}
  renderItem={({item: call}) => (
    <Card {...call}/>
  )}
/>

API Return:

{
  "Annotation": [
    {
      "id": 1,
      "dateIn": "2019-12-13T18:54:39.0248433+00:00",
      "message": "test1",
      "statusId": 1,
      "symbolId": 5,
      "symbol": {
        "id": 5,
        "status": "start",
      }
    },
    {
      "id": 2,
      "dateIn": "2019-12-13T14:23:10.6056632+00:00",
      "message": "test2",
      "statusId": 1,
      "symbolId": 2,
      "symbol": {
        "id": 2,
        "status": "end",
      }
    }
  ],
  "editedAnnotation": [
    {
      "Annotation": {
        "id": 3,
        "dateIn": "2019-12-13T19:28:10.6056632+00:00",
        "message": "test3",
        "statusId": 1,
        "symbolId": 2,
        "symbol": {
          "id": 2,
          "status": "start",
        }
      }
    },
    "id": 1,
    "dateEdit": "2019-12-13T22:27:23.6273816+00:00",
    "newMessage": "test3 updated",
    "annotationId": 3
    }
  ]
}

Upvotes: 1

Views: 727

Answers (1)

Vencovsky
Vencovsky

Reputation: 31713

You could use spread operator to mix both lists into only one list.

<FlatList
  data={[...(cards.Annotation || []), ...(cards.editedAnnotation || [])]}
  keyExtractor={call => String(call.id)}
  renderItem={({item: call}) => (
    <Card {...call}/>
  )}
/>

Or you could try using SectionList.

Upvotes: 3

Related Questions