Gilad Novik
Gilad Novik

Reputation: 4604

How to use Fetch api with arrayBuffer response type and React Native?

I'm currently using Fetch API with my RN project. It works well with text and json response types, but it doesn't work with arrayBuffer

let res = await fetch('http://example.com');
let data = await res.arrayBuffer();

Any ideas?

Upvotes: 12

Views: 6466

Answers (1)

tsn
tsn

Reputation: 838

It seems it hasn't been added in to the React Native implementation yet. In the mean time XMLHTTPRequest seems to have all the functionality of the browser version.

function get(url) {
    return new Promise((accept, reject) => {
        var req = new XMLHttpRequest();
        req.open("GET", url, true);
        req.responseType = "arraybuffer";

        req.onload = function(event) {
            var resp = req.response;
            if(resp) {
                accept(resp);
            }
        };

        req.send(null);
    });
}

...

let data = await get('http://example.com');

Note: This doesn't reject on errors and is left as an exercise to the reader ;)

Upvotes: 11

Related Questions