1
private _getListData(): Promise<ISPLists> { 
    Date.prototype.addDays = function(days) {
      var Date = new Date(this.valueOf());
      Date.setDate(Date.getDate() + days);
      return Date;
  };
  var today = new Date();

  var Startdate = today.toISOString().substring(0,10) + "T00:00:00.000Z";
var Enddate = today.toISOString().substring(0,10) + "T23:00:00.000Z";
var queryString = "&$Top=1&$filter=Today le datetime'" + Enddate + "' and Today ge datetime'" + Startdate + "'";

jQuery.ajax({
  url: encodeURI(_spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('" + ThoughtforthedayWebPart + "')/items?" + queryString),
  type: "GET",
  headers: {
      "Accept": "application/json; odata=verbose",
      "Content-Type": "application/json;odata=verbose",
  }
}).done(function (data) { console.log(data.d.results;});
}

Errors:

  1. _spPageContextInfo Cannot find name '_spPageContextInfo'. This is the error iam getting.

  2. cannot find name jQuery.

3.

Promise Error: A function whose declared type is neither 'void' nor 'any' must return a value.

  1. .done(function (data) { console.log(data.d.results}) Error: (local function)(data: any): void Use arrow function instead of function expression (no-function-expression)

Mikhail Zhuikov
  • 614
  • 1
  • 6
  • 19
Selvin
  • 41
  • 5

4 Answers4

2

Hi Selvin,

 1. In SPFX webpart, you have to use 'this.context.pageContext.web.absoluteUrl' to get URL using context
    2. You have to install jquery and then you have to import in webpart like this,
       Install -> npm i jquery
       Import -> import * as $ from 'jquery';
    3. Your function will be like this,
         public _getListData() {
            var today = new Date();
            var Startdate = today.toISOString().substring(0, 10) + "T00:00:00.000Z";
            var Enddate = today.toISOString().substring(0, 10) + "T23:00:00.000Z";
            var filterQuery = "?$top=1&$filter=Created  le datetime'" + Enddate + "' and Created ge datetime'" + Startdate + "'";<br>
            $.ajax({
               url: encodeURI(this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('T1')/items" + filterQuery),
               type: "GET",
               headers: {
                   "Accept": "application/json; odata=verbose",
                   "Content-Type": "application/json;odata=verbose",
               },
               success: function (data) {
                  var allData = data.d.results;
                  var datalen = data.d.results.length;
                  if (datalen == 0) {
                     console.log("No records available for today's date");
                  }
                  else {
                     console.log("Available Record:", allData);
                  }
               },
               error: function (err) {
                  console.log(JSON.stringify(err));
               }
            })
         }

Output in console

Regards,
Chandani Prajapati

0

private _renderListAsync(): void {

if (Environment.type === EnvironmentType.Local) {
this._getMockListData().then((response) => {
this._renderList(response.value);
});
}
else {
this._getListData()
.then((response) => {
this._renderList(response.value);
});
}
}

Iam getting an error in 'then' function. This is the error. Property 'then' does not exist on type 'void'

Selvin
  • 41
  • 5
0

import { Version } from '@microsoft/sp-core-library'; import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; import { IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-property-pane'; import { escape } from '@microsoft/sp-lodash-subset'; import './ThoughtforthedayWebPart.module.scss'; import * as strings from 'ThoughtforthedayWebPartStrings';

import MockHttpClient from './MockHttpClient'; import { SPHttpClientResponse, SPHttpClient, SPHttpClientConfiguration, ISPHttpClientOptions, } from '@microsoft/sp-http'; import {
Environment,
EnvironmentType
} from '@microsoft/sp-core-library'; import * as $ from 'jquery'; import 'jquery';

export interface ISPLists {
value: ISPList[];
}

export interface ISPList {
Title: string;
Quote: string;

}

export default class ThoughtforthedayWebPart extends BaseClientSideWebPart {

public _getListData() { var today = new Date(); var Startdate = today.toISOString().substring(0, 10) + "T00:00:00.000Z"; var Enddate = today.toISOString().substring(0, 10) + "T23:00:00.000Z"; var filterQuery = "?$top=1&$filter=Created le datetime'" + Enddate + "' and Created ge datetime'" + Startdate + "'"; $.ajax({ url: encodeURI(this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('Thoughtfortheday')/items" + filterQuery), type: "GET", headers: { "Accept": "application/json; odata=verbose", "Content-Type": "application/json;odata=verbose", }, // tslint:disable-next-line: no-function-expression success: function (data) { var allData = data.d.results; var datalen = data.d.results.length; if (datalen == 0) { console.log("No records available for today's date"); } else { console.log("Available Record:", allData); } }, // tslint:disable-next-line: no-function-expression error: function (err) { console.log(JSON.stringify(err)); } }); }

private _renderListAsync(): void {

if (Environment.type === EnvironmentType.Local) {
this._getMockListData().then((response) => {
this._renderList(response.value);
});
}
else {
this._getListData()
.then((response) => {
this._renderList(response.value);
});
}
}

private _getMockListData(): Promise {
return MockHttpClient.get(this.context.pageContext.web.absoluteUrl).then(() => {
const listData: ISPLists = {
value:
[
{ Title: 'Gandhi', Quote: 'Where there is will there is a way' },
{ Title: 'Modi', Quote: 'Desh Vasiyon' }, { Title: 'Rajiv', Quote: 'Try until u succeed' },

      ]  
      };  
  return listData;  

}) as Promise;
}

private _renderList(items: ISPList[]): void {
let html: string = '';

items.forEach((item: ISPList) => {  
  html += `  

    <div align="center">  ${item.Quote}</div>
      <div align="right"> ${'-'}  ${item.Title}</div> 

      `;  
});  
html += `</table>`;  
const listContainer: Element = this.domElement.querySelector('#spListContainer');  
listContainer.innerHTML = html;  

}

public render(): void {
this.domElement.innerHTML = <div class="thoughtfortheday}">
<div class="container">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
</div>
</div>
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white row}">
<div style="background-color:Black;color:white;text-align: center;font-weight: bold;font-size:18px;">Thought for the day</div>
<br>
<div id="spListContainer" />
</div>
</div>
</div>
;
this._renderListAsync();
}

protected get dataVersion(): Version { return Version.parse('1.0'); }

protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: strings.BasicGroupName, groupFields: [ PropertyPaneTextField('description', { label: strings.DescriptionFieldLabel }) ] } ] } ] }; } }

This is the entire code.

Selvin
  • 41
  • 5
0

Your full code of webpart will be like this:

import { Version } from '@microsoft/sp-core-library';
import {
  BaseClientSideWebPart,
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import styles from './TestWebPart.module.scss';
import * as strings from 'TestWebPartStrings';
import * as $ from 'jquery';

export interface ITestWebPartProps {
  description: string;
}

export default class TestWebPart extends BaseClientSideWebPart<ITestWebPartProps> {

  public render(): void {
    this._getListData();
    this.domElement.innerHTML = `
      <div class="${ styles.test}" id="tableData"></div>`;
  }

  public _getListData() {
    var today = new Date();
    var Startdate = today.toISOString().substring(0, 10) + "T00:00:00.000Z";
    var Enddate = today.toISOString().substring(0, 10) + "T23:00:00.000Z";
    var dynamicHtml = "<table border=1 width=100% style='border-collapse: collapse;'><tr><th>ID</th><th>Title</th>"
    var filterQuery = "?$top=1&$filter=Created  le datetime'" + Enddate + "' and Created ge datetime'" + Startdate + "'";
    $.ajax({
      url: encodeURI(this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('T1')/items" + filterQuery),
      type: "GET",
      headers: {
        "Accept": "application/json; odata=verbose",
        "Content-Type": "application/json;odata=verbose",
      },
      success: function (data) {
        //in query top=1 so it will return only 1 value so will directly use [0] item
        var allData = data.d.results[0];
        var datalen = data.d.results.length;
        if (datalen == 0) {
          dynamicHtml += "<tr>";
          dynamicHtml += "<td  colspan='2' style='text-align: center;'>Record not found.</td>";
          dynamicHtml += "</tr>";
          dynamicHtml += "</table>";
          $("#tableData").html(dynamicHtml);
        }
        else {
          dynamicHtml += "<tr>";
          dynamicHtml += "<td style='text-align: center;'>" + allData.ID + "</td>";
          dynamicHtml += "<td style='text-align: center;'>" + allData.Title + "</td>";
          dynamicHtml += "</tr>";
          dynamicHtml += "</table>";
          $("#tableData").html(dynamicHtml);
        }
      },
      error: function (err) {
        console.log(JSON.stringify(err));
      }
    })
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

If Record is found then output like this:

Found Image

If Record is not found then output like this:

Not Found Image Regards,
Chandani Prajapati