locked
Uncaught TypeError: Cannot read property 'post' of undefined RRS feed

  • Question

  • The below is my code:

    import * as React from 'react';
    import styles from './PostTest.module.scss';
    import { IPostTestProps } from './IPostTestProps';
    import { escape } from '@microsoft/sp-lodash-subset';
    import { TextField } from 'office-ui-fabric-react/lib/TextField';  
    import { IButtonProps, DefaultButton } from 'office-ui-fabric-react/lib/Button';  
    
    import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions } from '@microsoft/sp-http';
    
    
    import {
     Environment,
     EnvironmentType
    } from '@microsoft/sp-core-library';
    
    export interface IComponentState{
      title: string;
    }
    
    export default class PostTest extends React.Component<IPostTestProps, IComponentState> {
    
      constructor(props: IPostTestProps, state: IComponentState){
        super(props);
        this.state = ({
          title: ''
        });
    
        this._saveClicked = this._saveClicked.bind(this);
      }
    
      public render(): React.ReactElement<IPostTestProps> {
        return (
          <div className={ styles.postTest }>
            <div className={ styles.container }>
              <div className={ styles.row }>
                <div className={ styles.column }>
                  <span className={ styles.title }>Welcome to SharePoint!</span>
                  <p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>
                  <p className={ styles.description }>{escape(this.props.description)}</p>
                  <a href="https://aka.ms/spfx" className={ styles.button }>
                    <span className={ styles.label }>Learn more</span>
                  </a>
                  <TextField 
                    label="Standard" 
                    value={this.state.title}
                    onChanged={e => this.setState({ title: e })} 
                  />
                  <DefaultButton
                    onClick={this._saveClicked}
                  >
                  Save
                  </DefaultButton>
                </div>
              </div>
            </div>
          </div>
        );
      }
    
      private _saveClicked(): void {  
        alert('Hello ' + this.state.title);
        let requestlistItem: string = JSON.stringify({
          '__metadata': { "type": "SP.Data.ShipListItem" },
          "Title": this.state.title,
          "RequesterId":10
          });
        requestlistItem = requestlistItem.substring(1, requestlistItem .length-1);
        requestlistItem = '{' + requestlistItem +'}';
        console.log(requestlistItem);
    
        this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Ship')/items`, SPHttpClient.configurations.v1, {
          headers: {
          'Accept': 'application/json;odata=nometadata',
          'Content-type': 'application/json;odata=verbose',
          'odata-version': ''
          },
          body: requestlistItem
          })
          .then((response: SPHttpClientResponse) => {
            // Access properties of the response object. 
            console.log(`Status code: ${response.status}`);
            console.log(`Status text: ${response.statusText}`);
    
            //response.json() returns a promise so you get access to the json in the resolve callback.
            response.json().then((responseJSON: JSON) => {
              console.log(responseJSON);
            });
          });
      }   
    }
    

    When I press the "Save" button, I am getting the following error:

    Uncaught TypeError: Cannot read property 'post' of undefined.

    I already have a sharepoint list called "Ship". 

    Tuesday, January 22, 2019 8:29 AM

Answers

All replies

  • Just noticed that, the problem comes if I use React framework template. If I use "no-framework" this does not come.
    Tuesday, January 22, 2019 9:48 AM
  • Hi,

    Please use  this.props.spHttpClient.post to check if it works in React framework.

    The following article with code about CRUD Operations for list item using ReactJS and SharePoint REST API in SPFx for your reference.

    https://www.c-sharpcorner.com/article/sharepoint-framework-crud-operations-using-react-js/

    More example code about SPFx is here:

    https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Wednesday, January 23, 2019 6:53 AM
  • Hi,

    Would you please provide us with an update on the status of your issue?

    Best Regards,
    Dennis

    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Monday, January 28, 2019 8:18 AM
  • This error occurs in Chrome Browser when you read a property or call a method on an undefined object . Uncaught TypeError: Cannot read property of undefined  error is probably easiest to understand from the perspective of undefined, since undefined is not considered an object type at all (but its own undefined type instead), and properties can only belong to objects within JavaScript. There are a few variations of this error depending on the property you are trying to access. Sometimes instead of undefined it will say null.


    Wednesday, May 29, 2019 6:03 AM