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?
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.
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.
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:
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.
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With