Home > Software design >  Why flatlist is not sorted after sorting the array?
Why flatlist is not sorted after sorting the array?

Time:07-17

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",
  }
]

CodePudding user response:

In your first call to setListTab you're setting the state to result.data.categoriesData.

Then you're trying to sort listTab, but in this moment, the state still empty [], because react have not rendered it yet.

Sort the results of your request before, than later set the state.

Something like this:

result.data.categoriesData.sort()...

setListTab([defaultListTab, ...result.data.categoriesData]);

CodePudding user response:

the problem is that listTab is not updated instantly because setListTab is an async operation

change your code like this

const defaultListTab = {id: 18, name: "All"};
const [listTab, setListTab] = React.useState([]);

.then(function (result) { 
    setListTab(result.data.categoriesData)
    
    setListTab(listTab => {
      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;
    });
    return [defaultListTab, ...listTab]

    })

when you use a callback inside you setState function it will get the updated value

  • Related