Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 736
Gilad Novik Avatar asked Apr 30 '17 22:04

Gilad Novik


People also ask

What are the functions of React Native fetch API?

Below given are the prominent functions. 1. Initialize Constructor of React Native Class First, we need to define two different states, one being a Boolean variable and other being an array into which data loaded by fetch API will be stored. The Boolean variable set to true in constructor signifies that data loading from URL has started.

What is the difference between fetch API and response?

It takes multiple arguments, including the API endpoint's URL, i.e., the path of the resource you are interested in fetching. Fetch API uses two objects, Request and Response. This Response object holds the data sent by the API. Fetch sends the Request and returns a promise, which is resolved to the Response object when the request completes.

Is there an alternative to fetch in react?

Your code should run without any issues: One alternative to Fetch is Axios, which is compatible for Node, React and React Native. In addition to making GET requests, this module can even allow you to make POST, PUT and DELETE requests. To retrieve data using the Axios library, write the following code:

What is the return type of await fetch response?

The response object returned by await fetch supports multiple functions for different data formats, which include: response.json: Returns data as a JSON Object. response.text: Returns data in raw text. response.formData: Returns data as FormData. response.blob: Returns data as a Blob Object.


1 Answers

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 ;)

like image 95
tsn Avatar answered Sep 16 '22 13:09

tsn