Home > Mobile >  React native sorts array in useEffect but does not print it correctly
React native sorts array in useEffect but does not print it correctly

Time:09-21

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:

  1. When you load it, it should be filtered by first_name. It is not showing it sorted.
  2. when you click on L to sort by last_name, it displays the data sorted by first_name
  3. Then when you click on F to sort by first_name, it displays the data sorted by last_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.

CodePudding user response:

LocalCompares doesn't work with sort you need to use it like this:

 useEffect(() => {
    console.log("promoters changed", { filterByName });
    let filteredResults;
    if (filterByName) {
      filteredResults = [...filteredPromoters].sort((a, b) => {
        if ( filterByName === "first") {
            if(a.first_name < b.first_name) { return -1; }
            if(a.first_name > b.first_name) { return 1; }
            return 0;
        } else {
            if(a.first_name > b.first_name) { return -1; }
            if(a.first_name < b.first_name) { return 1; }
            return 0;
        }
      }
      );
    }
    setFilteredPromoters(filteredResults);
  }, [filterByName]);

I create a working example you can check it from here.

CodePudding user response:

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.

  • Related