I'm trying to implement a Sort component that sort my items by name or ID.
This is my code:
const data = [
{
id: 1,
name: "Gianni",
},
{
id: 2,
name: "Alvaro",
},
{
id: 3,
name: "Zuzzurello",
},
{
id: 4,
name: "Stefanino",
},
{
id: 5,
name: "Bertone",
},
];
function App() {
const [items, setItems] = useState(data);
const [sort, setSort] = useState("");
useEffect(() => {
if (sort === "name") {
const temp = [...items];
temp.sort((a, b) => a.name - b.name);
setItems(temp);
console.log("sort by name!");
} else if (sort === "number") {
const temp = [...items];
temp.sort((a, b) => a.id - b.id);
setItems(temp);
console.log("sort by number!");
}
}, [sort]);
return (
<main>
<form>
<label htmlFor="">sort by</label>
<select name="sort" id="sort" onChange={(e) => setSort(e.target.value)}>
<option value="">do nothing</option>
<option value="name">by name</option>
<option value="number">by number</option>
</select>
</form>
{items.map((item, index) => {
const { id, name } = item;
return (
<article key={index}>
<h2>{name}</h2>
<h4>{id}</h4>
</article>
);
})}
</main>
);
}
The select input works: "setSort" changes in my State. The useEffect works too: when sort changes, I get those messages in the console.
The problem is that the sort method in the useEffect doesn't work at all. setCollection in my useEffect does NOT update the status with the new sorted array and it doesn't trigger a re render.
When i put "items" in the dependencies array, it throws an infinite loop instead.
I have no clue. Thanks!