简体   繁体   中英

Uncaught TypeError: Cannot read property 'fetch' of undefined

I am doing a sample ReactJS App, where I am trying to send form data thro' RestAPI POST. Code snippets are given below, but, it doesn't work.

Component's render() is given below. Upon filling form, when user clicks "submit" button, 'handleSubmit' is invoked.

render() {
    return(
    <button 
    label="Submit" 
    onClick={this.handleSubmit}>
    Submit
    </button>
}

Definition of 'handleSubmit' is given below, It errors out here as "Uncaught TypeError: Cannot read property 'fetch' of undefined" .

handleSubmit() {

    this.fetch('https://example.domain.com/api/v1/task/actual', {
        method: 'POST',
        body: JSON.stringify({
            first_name: this.state.first_name,
            last_name: this.state.last_name
        })
        }).then(res => console.log('Success:', JSON.stringify(res)))
      .catch(error => console.error('Error:', error));
}

Just for clarity, I am sharing definition of fetch as well. AccessToken is fine. It works fine for other components.

fetch(url, options) {
        const accessToken = 'Bearer ' + auth.getAccessToken();
        const headers = {
            'Content-Type': 'application/json',
            'Authorization' : accessToken
        }
        return fetch(url, {
            headers,
            ...options
        })
  }

I missing out on something and I couldn't figure it out. Kindly advise.

The reason why fetch is undefined is because this is not the component. If you change your handleSubmit function definition to be:

handleSubmit = () => {

Then your code should work. Note that this might require altering your transpiling setup. Alternatively, you can bind your handleSubmit function in your constructor so that it has the correct this .

Within your constructor add the following code.

this.handleSubmit = this.handleSubmit.bind(this);

Another thing is to make sure fetch function is present in this instance. That fetch is declared within your component class or if you import it from some external file add the following line as well in your constructor.

this.fetch = fetch.bind(this);

Explained pretty well in React docs. Go ahead read it.
https://reactjs.org/docs/handling-events.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM