From c5cbcd841b6013ca3be1b7e0ed2793c430910bb1 Mon Sep 17 00:00:00 2001 From: Florian Heft Date: Tue, 5 Nov 2019 13:28:48 +0100 Subject: [PATCH] Change XHR response listener to onloadend in xhr effect * Neither onload nor onerror get called on XMLHttpRequest request timeouts, so we don't get any response at all if a request times out. Onloadend on the other hand gets called for any load-ending conditions, even onabort and consequential ontimeout (see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/loadend_event) So with this change we can guarantee to eventually trigger either the onSuccess or the onError event of the xhr effect. --- src/batteries.js | 2 +- src/batteries.test.js | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/batteries.js b/src/batteries.js index 5641ce9..76d4883 100644 --- a/src/batteries.js +++ b/src/batteries.js @@ -86,7 +86,7 @@ effector( for (let name in headers) { xhr.setRequestHeader(name, headers[name]); } - xhr.onload = xhr.onerror = function() { + xhr.onloadend = function() { switch (this.status) { case STATUS_OK: case STATUS_CREATED: diff --git a/src/batteries.test.js b/src/batteries.test.js index 0bcaf7b..088f7ee 100644 --- a/src/batteries.test.js +++ b/src/batteries.test.js @@ -100,7 +100,7 @@ describe("xhr effect", () => { const xhr = xhrs[0]; [200, 201, 202, 204, 206, 304].forEach(status => { trigger.mockClear(); - xhr.onload.call({ + xhr.onloadend.call({ status: status, statusText: "${status}", response: "response", @@ -121,7 +121,7 @@ describe("xhr effect", () => { statusText: "Server error", response: "response", }; - xhr.onload.call(response); + xhr.onloadend.call(response); expect(trigger).toHaveBeenCalledTimes(1); expect(trigger).toHaveBeenCalledWith("error", "foo", response); }); @@ -134,7 +134,7 @@ describe("xhr effect", () => { statusText: "OK", response: "response", }; - xhr.onload.call(response); + xhr.onloadend.call(response); expect(trigger).not.toHaveBeenCalled(); }); it("ignores errors if onError is unset", () => { @@ -146,7 +146,7 @@ describe("xhr effect", () => { statusText: "Server error", response: "response", }; - xhr.onload.call(response); + xhr.onloadend.call(response); expect(trigger).not.toHaveBeenCalled(); }); });