I'm creating a flatlist that outputs array of object from an API. Before outputting the array, It will be sorted alphabetically and another data will be added at the top of the array. The problem is that the data is not sorted when rendered in the flatlist and the new data that was added is missing.
const defaultListTab = {id: 18, name: "All"};
const [listTab, setListTab] = React.useState([]);
.then(function (result) {
setListTab(result.data.categoriesData)
listTab.sort(function (a, b){
if(a.name.toLowerCase() < b.name.toLowerCase()) {
return -1;
} else if(a.name.toLowerCase() > b.name.toLowerCase()) {
return 1;
}
return 0;
});
setListTab(listTab => [defaultListTab, ...listTab])
)};
return () => abortCont.abort();
This is what the array looks like originally:
Array [
Object {
"id": 29,
"name": "Fruit",
},
Object {
"id": 30,
"name": "Vegetable",
},
Object {
"id": 31,
"name": "Dessert",
}
]