I have a component that uses an instance of <iron-ajax>
to retrieve data from the back-end, and I would like to use <iron-request>
to send updates such as POST/DELETE requests.
Everything works perfectly the first time around. However if the request is invoked again, I get an error:
Uncaught TypeError: Cannot read property 'then' of undefined
My template definition looks like this:
...
<iron-ajax id="ajax" auto verbose
url="/cart-api/"
last-response="{{ajaxResponse}}"
handle-as="json">
</iron-ajax>
<iron-request id="xhr"></iron-request>
...
In my component script I use the send()
method of <iron-request>
to send a POST:
var me = this;
this.$.xhr.send({
url: "/cart-api",
method: "POST",
body: JSON.stringify(entry)
}).then(function() {
me._refresh();
}, function() {
console.error("POST failed");
});
The error message indicates that send
has returned undefined
rather than a valid Promise object.
So my question is this: is an <iron-request>
element actually reusable? Do I need to do anything to refresh or reinitialize it?
UPDATE
Thanks to @Zikes I have updated my code as follows:
<iron-ajax id="ajaxGet" auto
url="/cart-api/"
last-response="{{ajaxResponse}}"
handle-as="json">
</iron-ajax>
<iron-ajax id="ajaxPost" url="/cart-api" method="POST" on-response="_refresh"></iron-ajax>
<iron-ajax id="ajaxDelete" method="DELETE" on-response="_refresh"></iron-ajax>
insertEntry: function(entry) {
this.$.ajaxPost.body = JSON.stringify(entry);
this.$.ajaxPost.generateRequest();
},
_handleRemove: function(e) {
var entry = e.currentTarget.entry;
this.$.ajaxDelete.url = "/cart-api/" + entry.id;
this.$.ajaxDelete.generateRequest();
},
_refresh: function() {
this.$.ajaxGet.generateRequest();
},