[Vuejs]-Nuxt.js Hackernews API sort posts by time desc newer ones first

0👍

The API that you’re using is indeed the official one (listed at the bottom of the official HN page).
Unfortunately, there is nothing integrated regarding any kind of sort via the API itself.

You will need to use the .sort method to run on each object’s date or similar field.

If we take that given URL with all the current posts: https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty
We can see that each one of them is ordered based on upvotes. Hence, the array that you’re receiving is full of objects like that one.

Once you have your huge array (in your stories state), it’s a matter of running .sort on the time field which is nothing more than a UNIX timestamp.


So given the following subset of data (as a super simplified example)

stories = [
  { name: "On the Gift of Longhand", time: 1670073398 },
  { name: "Mac OS 9", time: 1670259607 },
]

you can run the following to have them sorted by "freshest" first

stories.sort((a, b) => b.time - a.time)

gives the following

[
  {
    "name": "Mac OS 9",
    "time": 1670259607 // aka December 5th
  },
  {
    "name": "On the Gift of Longhand",
    "time": 1670073398 // aka December 3rd
  }
]

The rest of the work is a matter of properly organizing your data and looping on it in your Vue code.

It may be quite un-efficient because it’s a huge array (could use a backend middleware server to help the performance). Of course, a native API thing would be the best but I think that it’s made on purpose (and hence will never come live).


Update

This is how you would sort the sorties depending on their time, regarding the starting point of my previous answer.

watch(responseSubset, async (newV) => {
  const unsortedStories = await Promise.all(responseSubset.value.map(async (id) => await $fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`)))
  stories.value = unsortedStories.sort((a, b) => b.time - a.time)
})

Leave a comment