How to sort data by createdAt, order by DESC from strapi
Javascript
3 months ago

How to sort data by createdAt, order by DESC from strapi

Strapi provide results in Ascending order. Which means the data being fetched will have the oldest first and the newest last. But in this guide we will see how to limit data, sort data and set the order to Descending using REST API

I was working on a project and wanted to order the fetched result without writing my own function. And after some research, I found it was very easy to do with REST API

The post assume you have your strapi project setup and you have added some content types to fetch. And your server is running, if not, start your server

In my project, I used axios, you can use JavaScript fetch method and still get the same results

Sorting using one or more fields

Syntax: sort: ['title', 'slug', …..]

Usage

http://localhost:1337/posts?_sort=createdAt

Here I am sorting the fetched data by the createdAt field.

Sorting using one or more fields and set the order

Syntax: sort: ['title: ASC', 'slug:DESC', …..]

Usage

http://localhost:1337/posts?_sort=createdAt:desc

To add more fields to sort in the URL, use ampersand (&)

Limiting the results

Limit and Sort are very similar, we can limit the number of result by simply adding _limit=.

Example

http://localhost:1337/posts?_limit=4&_sort=createdAt:desc

Here I want to get only 4 posts and order by desc, that means newest first

Fetching data using a nested field

I had some problem fetching data, where category name matches a string. The reason is because the category field is a related field to the posts am fetching, hence the category field is an object

fetching_data.jpg

Here you can see that the category is an object that has many fields

To use a particular field inside the category object we use period (.) to point the field

example

http://localhost:1337/posts?category.name=Journey&_limit=4&_sort=createdAt:desc

To use this parameters with axios, we simply use axios.get(url).

You can learn more about REST API parameters from the REST API Documentation

I hope this is helpful.

Don't forget to hit the like button, share this post and also follow me on socials… Gracias 😎

Category:  
Javascript


Tags:  
Jamstack
React
Gatsby
css