Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer 1.0: Multiple calls to send() method of iron-request

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();
},
like image 601
Neil Bartlett Avatar asked Jun 02 '15 17:06

Neil Bartlett


1 Answers

The <iron-ajax> component spawns a new <iron-request> for each new request made: https://github.com/PolymerElements/iron-ajax/blob/master/iron-ajax.html#L442

If you are looking for reusability (and other nice features like debounce) you would probably be better off using the <iron-ajax> component.

like image 194
Zikes Avatar answered Oct 03 '22 21:10

Zikes