0
I am using React Hooks to sort an array list by the 'points' item after I update an object item. After much tinkering with the code I managed to sort the Array in the 'Sorted' variable using useMemo (which I confess I didn’t understand very well how it works).
But now I can’t use useState setStudents(Sorted) to transfer this variable to the interface. If I put setStudents(Sorted) inside the useEffect or changePontuation function it ignores changing the 'points' variable'
function App() {
const [students, setStudents] = useState([
{ name: 'Letícia Lima', id: 1, points: 12090 },
{ name: 'Flávia Augusto', id: 2, points: 11276 },
{ name: 'Douglas Adams', id: 3, points: 11181 },
{ name: 'Carina Rosa', id: 4, points: 11019 },
{ name: 'Amanda Nunes', id: 5, points: 10981 },
{ name: 'Fabrício Frazoli', id: 6, points: 10756 },
]);
useEffect(() => {
const timer = setTimeout(() => {
changePontuation();
}, 2000);
console.log(sorted);
}, []);
function changePontuation() {
let changedStudents = [...students];
changedStudents[2] = { ...students[2], points: 11297 };
setStudents(changedStudents);
console.log('executando função interval');
}
const sorted = React.useMemo(() =>
students.slice().sort((a, b) => b.points - a.points)
);
console.log(sorted);
Would you mind putting in the code as a favor? useMmo is used to "memorize the result" of a heavy computation , in your case it is not doing anything because you are not passing the dependencies.
– iwaduarte