Question

I'm trying to add an item in SharePoint Online list using SPFx solution where I'm using React JS to perform the action.

Below is the copied code, when debugging it says that:

"VM242:1 Uncaught TypeError: Cannot read property 'spHttpClient' of undefined"

Please have a look at the below code and let me know if I'm missing out on any thing.

I'm just trying to add an item in list called test.

function _alertClicked(): void {
  alert('Clicked');
  //Custom
  const body: string = JSON.stringify({
    'Title': `Item ${new Date()}`
  });
  this.context.SPHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('test')/items`,
    SPHttpClient.configurations.v1,
    {
      headers: {
        'Accept': 'application/json;odata=nometadata',
        'Content-type': 'application/json;odata=nometadata',
        'odata-version': ''
      },
      body: body
    })
    .then((Response: SPHttpClientResponse): Promise<IListItem> => {
      return Response.json();
    })
    .then((item: IListItem): void => {
      this.updateStatus(`Item 'Test' Successfully Created`);
    }, (error: any): void => {
      this.updateStatus('Error' + error);
    });

}

Note: I'm using fabric controls on the page.

No correct solution

OTHER TIPS

Declare a props of SPHttpClient type in your Webpart's Props.ts file as below :

import { SPHttpClient } from "@microsoft/sp-http";

export interface WebpartProps { 
   spHttpClient: SPHttpClient;
}

Go to your Webpart's .ts file :

import { SPHttpClient, SPHttpClientConfiguration, SPHttpClientResponse, ODataVersion, ISPHttpClientConfiguration } from '@microsoft/sp-http';

public render(): void {
   const element: React.ReactElement<IHomepageProps> = React.createElement(
     Webpart, //this name will be your webpart name
     {
        spHttpClient: this.context.spHttpClient,
     }
   );
 }

Now you should be able to pass it in your .tsx file as below :

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