0
votes

I'm trying to fetch items from a specific view of a Sharepoint list in SPFX using @pnp/sp library but I'm unable to do so. I'm able to fetch the view properties and fields of the list. I didn't find anything as such to fetch the items of that view. How will I be able to acheive the same and also my list contains Lookup columns as well.

1

1 Answers

0
votes

There is no direct function which supported to get items from specific view. Instead, it's necessary to get CAML Query from the ListView and then get items based on CAML Query, here is a code snippet for your reference:

import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/views";
import "@pnp/sp/items";
import { SPHttpClient, SPHttpClientConfiguration, SPHttpClientResponse,
  ISPHttpClientConfiguration } from '@microsoft/sp-http';

  public getListViewData():void{
    let listName = "JqueryList"; //The display name of the sharepoint list.
    let viewName = "All Items"; //The View Name

    HelloWorldWebPart.getViewQueryForList(listName,viewName).then((res:any) => {
        HelloWorldWebPart.getItemsByViewQuery(listName,res).then((items:any[])=>{
            items.forEach((item:any) => {
                console.log(item);
            });
        })
    }).catch(console.error);
}

//First method that retrieves the View Query
public static getViewQueryForList(listName:string,viewName:string):Promise<any> {
    let listViewData = "";
    if(listName && viewName){
        return sp.web.lists.getByTitle(listName).views.getByTitle(viewName).select("ViewQuery").get().then(v => {
            return v.ViewQuery;
        });
    } else {
        console.log('Data insufficient!');
        listViewData = "Error";
    }
}


//Second method that retrieves the View data based on the View Query and List name
public static getItemsByViewQuery(listName:string, query:string):Promise<any> {
    const xml = '<View><Query>' + query + '</Query></View>';
    return sp.web.lists.getByTitle(listName).getItemsByCAMLQuery({'ViewXml':xml}).then((res:SPHttpClientResponse) => {
        return res;
    })
}

Here is a similiar thread for your reference:

How get sharepoint list items by view(s) in spfx?