I have the next code:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [state, setState] = useState([
{ name: "Edward", value: 21 },
{ name: "Sharpe", value: 37 },
{ name: "And", value: 45 },
{ name: "The", value: -12 },
{ name: "Magnetic" },
{ name: "Zeros", value: 37 }
]);
const sorting = () => {
const a = state.sort(function (a, b) {
if (a.name > b.name) {
return 1;
}
if (a.name < b.name) {
return -1;
}
return 0;
});
setState(a);
};
return (
<div className="App">
<table>
<tr>
<th>Firstname</th>
<th>data</th>
</tr>
{state.map((i) => {
return (
<tr key={i.name}>
<td>{i.name}</td>
<td>{i.value}</td>
</tr>
);
})}
</table>
<button onClick={sorting}>sort</button>
</div>
);
}
Clicking on the button i want to trigger the next function:
const sorting = () => {
const a = state.sort(function (a, b) {
if (a.name > b.name) {
return 1;
}
if (a.name < b.name) {
return -1;
}
return 0;
});
setState(a);
};
Which should sort the data from table, but it does not happens.
Question: Why my function does not work? ow to solve the issue that i described above? Note: when i will click on the button the data from table should change the order.
