Question

This seems like a very basic question but I can't figure it out. Using pnpjs I want to retrieve the 50 most recently created items, oldest first, newest last.

I can only manage to get them in the wrong order:

 const items = await this.spClient.web.lists.getByTitle(this.spList).items
            .top(50)
            .orderBy("Created",false)
            .get();

If I change this to

 const items = await this.spClient.web.lists.getByTitle(this.spList).items
            .top(50)
            .orderBy("Created",true)
            .get();

the order is right but I get the 50 first items.

So how to get the items I want sorted the way I want?

Was it helpful?

Solution

You will need to do both the REST orderBy, and then use JavaScript to reverse the array of items in the returned results.

The problem is thus: In order for the REST API to return only the n most recent items, you have to provide the ODATA orderBy the created date in Descending order. But, if you want to use or display those same n items in any other order than that which you retrieved, you will need to re-sort the results in your code.

OTHER TIPS

We can also use caml query to get the 50 items and sorted. Below is not an exact working code, I haven't tested, but it will give you an idea to implement it.

const xml = "<View><ViewFields><FieldRef Name='ID' /><FieldRef Name='Title' /></ViewFields><Query><OrderBy><FieldRef Name='Created' /></OrderBy></Query><RowLimit>50</RowLimit></View>";    
const q: CamlQuery = {
    ViewXml: xml,
};    
const items = pnp.sp.web.lists.getByTitle("SPPnPJSExampleList").getItemsByCAMLQuery(q)

Try using below if this works for you:

const items = await this.spClient.web.lists.getByTitle(this.spList).items
             .orderBy("Created",true)
             .top(50)
             .get();

For descending order you can use orderBy("Created, false).

Update:

As @willman mentioned, You need to get the data in reverse order using orderBy("Created, false) and then you need to reverse the array in your code when you get the complete data.

PnPJS - Working With: Items.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top