Home > database >  In my react hooks the display of record based on latest date is not happening
In my react hooks the display of record based on latest date is not happening

Time:06-12

I would like to display the latest record based on date on top of the list in my react hooks app. By using moment.js, will it automatically sort the latest record on top of the list ? Could someone please advise how can we achieve that ?

CSB link:

https://codesandbox.io/s/wild-cache-dkt924?file=/src/App.js:156-1140

const data = [
  {
    name: "Apple",
    type: "Fruit",
    date: "2022-06-10T05:49:24.000Z"
  },
  {
    name: "Beans",
    type: "Vegtables",
    date: "2022-07-10T10:49:24.000Z"
  },
  {
    name: "Oranges",
    type: "Fruit",
    date: "2022-05-10T07:49:24.000Z"
  }
];
export default function App() {
  const [fruitData, setFruitsData] = useState([]);
  useEffect(() => {
    setFruitsData(data);
  }, []);
  return (
    <div className="App">
      <div className="column">
        <h2>Latest Data</h2>

        <div className="announcebox" id="style-7">
          {fruitData.map(({ id, name, date }) => (
            <div key={id}>
              <div className="newsDate">
                {moment(date).format("DD-MM-YYYY hh:mm:ss")}
              </div>
              <p>
                <div className="annoucement updates">{name}</div>
              </p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

CodePudding user response:

Update your useEffect to this

useEffect(() => {
    data.sort(function(a,b){
      return new Date(b.date) - new Date(a.date);
    });
    setFruitsData(data);
  }, []);
  • Related