I'm getting an error "Unhandled rejection TypeError: Cannot set property 'resultMessage' of undefined" when I try to use fetch in Aurelia to post form's data and print out a message on the same webpage if it succeeded (${resultMessage}).
this.resultMessage = "New book added"; <= this line is resulting in error
add.js:
import {HttpClient, json} from 'aurelia-fetch-client'
export class AddBooks{
bookData = {}
constructor() {
this.resultMessage = ""
}
activate() {
let client = new HttpClient();
}
addBook() {
let client = new HttpClient();
client.fetch('{address}', {
'method': "POST",
'body': json(this.bookData)
})
.then(function(response) {
return response.json();
})
.then(function(data) {
if(data.id) {
console.log(JSON.stringify(data));
this.resultMessage = "New book added";
}
});
}
}
add.html:
<template>
<form id="bookaddform" method="post" submit.delegate="addBook()">
<div>
<label for="bookTitle">Book Title</label>
<input id="bookTitle" type="text" name="bookTitle" value.bind="bookData.title">
</div>
<div>
<label for="bookPrice">Book Price</label>
<input id="bookPrice" type="number" name="bookPrice" value.bind="bookData.price">
</div>
<div>
<label for="bookDescription">Book Description</label>
<input id="bookDescription" type="text" name="bookDescription" value.bind="bookData.description">
</div>
<input type="submit" value="Add your book">
</form>
${resultMessage}
</template>
response-json
{
"id": "2",
"errors": []
}