Home > Software design >  React sorting doesn't work right on the first try
React sorting doesn't work right on the first try

Time:10-24

I have the following component with a select that changes my sorting state

const [sorting, setSorting] = useState(""); 
const priceAsc = (r1, r2) => {
    return r2.euroPrice - r1.euroPrice;
  };
  const priceDesc = (r1, r2) => {
    return r1.euroPrice - r2.euroPrice;
  };
  useEffect(() => {
    console.log(sorting);
    switch (sorting) {
      case "price:asc":
        console.log("here!");
        setRoutes(routes.sort(priceAsc));
        break;
      case "price:desc":
        console.log("now here!");
        setRoutes(routes.sort(priceDesc));
        break;
      default:
        setRoutes(routes.sort(priceAsc));
        break;
    }
  }, [sorting]);

The problem is if the first time I select price ascending option, my program outputs

price:asc
here!

which should mean it sorts my array ascending by price, but it's actually sorting it descending. If I change the select then it sorts it like I would expect. So this only happens on the very first time I choose the ascending option

CodePudding user response:

Array.sortsorts the array in place. Because the state must be treated as immutable, you must update the state with a new array.

setRoutes([...routes.sort(priceAsc)])
  • Related