-1

I try to sort my array to revers and I use the reverse() function but it doesn't affect to view. I must to change the file and save it then I can see the changes.

Items.js:

import { useState } from "react";

const Items = (props) => {
  const [myArray, setMyArray] = useState([
    {
      pId: 1,
      title: "P 1",
    },
    {
      pId: 2,
      title: "P 2",
    },
    {
      pId: 3,
      title: "P 3",
    },
    {
      pId: 4,
      title: "P 4",
    },
  ]);

const handleSort = () => {
    console.log("before", myArray);
    setTimeout(() => {
      setMyArray(myArray.reverse());
      console.log("after", myArray);
    }, 500);
  };

  return (
     <div>
      {myArray.map((a) => (
        <span key={a.pId} className="m-3">
          {a.title}
        </span>
      ))}
       <button onClick={handleSort}>reverse</button>
     </div>
  );

};

export default Items;

enter image description here enter image description here

Amir Hossein
  • 916
  • 2
  • 13
  • 38

1 Answers1

1

You are reversing an array of objects. use the spread operator to spread the elements of your array.

This should work fine.

  let myArray = [
    {
      pId: 1,
      title: "P 1",
    },
    {
      pId: 2,
      title: "P 2",
    },
    {
      pId: 3,
      title: "P 3",
    },
    {
      pId: 4,
      title: "P 4",
    }
  ]
console.log([...myArray].reverse());
Amr
  • 646
  • 1
  • 6
  • 21