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.