0

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

2 Answers 2

1

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]);
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

i tried your method but the flatlist doesnt show any of the data. After the then(), I implement a return () => abortCont.abort();. Having the return inside then() would ignore the abort(), right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.