typescriptrestsharepoint-onlinesharepoint-listsharepointframework

How can I retrieve a list view's items using SharePoint Framework's TypeScript API?


Given the named view of a certain SharePoint Online list, how can I retrieve the view's items with TypeScript that's part of a web part running in the same tenant as the list?


Solution

  • With:

    import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions } from '@microsoft/sp-http';
    

    And given:

    List: List1

    and

    View: View1

    This SPFX REST API code:

      const executeJson = (endpointUrl, payload) => {
        const opt: ISPHttpClientOptions = { method: 'GET' };
        if (payload) {
          opt.method = 'POST';
          opt.body = JSON.stringify(payload);
        }
        return this.context.spHttpClient.fetch(endpointUrl, SPHttpClient.configurations.v1, opt);
      };
      const getListItems = (webUrl,listTitle, queryText) => {
        var viewXml = '<View><Query>' + queryText + '</Query></View>';
        var endpointUrl = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems"; 
        var queryPayload = {'query' : { 'ViewXml' : viewXml } };
        return executeJson(endpointUrl, queryPayload);
      };
      const getListViewItems = (webUrl,listTitle,viewTitle) => {
        var endpointUrl = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
        return executeJson(endpointUrl, null).then((response: SPHttpClientResponse) => { return response.json(); })
        .then(data => {         
          var viewQuery = data.value;
          return getListItems(webUrl,listTitle,viewQuery); 
        });
      };
    
      const url = this.context.pageContext.site.absoluteUrl;
      getListViewItems(url,'List1','View1')
      .then((response: SPHttpClientResponse) => { return response.json(); })
      .then(response=>{
        for (var item of response.value) {
          console.log(item);
        }
      });
    

    will print the list view's items to console.

    Thank you: Vadim Gremyachev's SharePoint 2013 answer