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);