0

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.

  • You are missing to pass webpart context in your .tsx file. Check this article for step by step demo. – Ganesh Sanap Oct 11 '19 at 7:49
  • How do I pass the context ? Can you please share a snippet of code or reference pls – Muskan Oct 11 '19 at 7:52
  • You can pass it in props of react class. check the reference in above comment. – Ganesh Sanap Oct 11 '19 at 7:53
0

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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.