user3362908
user3362908

Reputation: 443

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.

Upvotes: 0

Views: 3260

Answers (3)

Aditya
Aditya

Reputation: 21

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

Upvotes: 0

Shubham Gupta
Shubham Gupta

Reputation: 2646

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);

Upvotes: 0

Matt Way
Matt Way

Reputation: 33209

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.

Upvotes: 2

Related Questions