Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
Why flatlist is not sorted after sorting the array?

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",
  }
]
about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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]);
about 4 years ago · Santiago Gelvez Report

0

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!