Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort an array with react hooks

I'm doing a simple sort of an array with react hooks, but its not updating state. Can anyone point out what I'm going here?

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const dogs = [{ name: "fido", age: 22 }, { name: "will", age: 50 }];

function App() {
  const [dogList, setDogList] = useState(dogs);

  const sortByAge = () => {
    const sorted = dogList.sort((a, b) => {
      return b.age - a.age;
    });
    setDogList(sorted);
    alert(sorted[0].name);
  };

  return (
    <div>
      {dogs.map((dog, i) => {
        return <p key={i}>{dog.name}</p>;
      })}
      <div onClick={sortByAge}>sort by age</div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
like image 402
seattleguy Avatar asked Sep 24 '19 20:09

seattleguy


1 Answers

First: because Array.prototype.sort() is in place, clone before you sort:

const sorted = [...dogList].sort((a, b) => {
  return b.age - a.age;
});

Without this the change detection will not detect the array changed.

You call map on dogs. Fix:

  return (
    <div>
      {dogList.map((dog, i) => {
        return <p key={i}>{dog.name}</p>;
      })}
      <div onClick={sortByAge}>sort by age</div>
    </div>
  );

Demo: https://jsfiddle.net/acdcjunior/kpwb8sq2/1/

like image 57
acdcjunior Avatar answered Nov 15 '22 00:11

acdcjunior