What am I doing wrong here? https://snack.expo.dev/@kickbk/names
Click on F to sort by first_name
or L to sort by last_name
.
You will see that:
- When you load it, it should be filtered by
first_name
. It is not showing it sorted. - when you click on L to sort by
last_name
, it displays the data sorted byfirst_name
- Then when you click on F to sort by
first_name
, it displays the data sorted bylast_name
In fact, it sorts the data correctly, but only renders it the next time you sort it. Why?
I made it very easy to follow on the issue I’m getting. Just check the logs and see what it prints.
2
Answers
I learned something today. The reason sorting was not working properly with my example was because sort modifies the array in place, and you can't directly modify state variables. Creating a new array with a spread operator is a way to handle it:
[...filteredPromoters].sort
, which is also what makes Louay's example work. Although it is a working solution, I believe it's important to mark this explanation as the actual solution to the problem.LocalCompares
doesn’t work with sort you need to use it like this:I create a working example you can check it from here.