krave
krave

Reputation: 1919

How to use fetch API to get an Array back?

I have an API which will return an array to me. I tried to use fetch API to get the array back. I know that if I use fetch to acquire some data, the real body in the response is ReadableStream. I usually to deal with it by response.json() in then function if data is json. What I don't know is how to deal with array data?

Upvotes: 1

Views: 25673

Answers (1)

Nijikokun
Nijikokun

Reputation: 1524

If your API is not returning a JSON array [1,2,3] then you can use the .text function to get the raw value:

fetch('/api/text').then(function(response) {
  return response.text()
}).then(function (text) {
  // parse the text here how you want, for csv:
  // return text.split(',')
})

Otherwise you can simply just use the .json method to get the array value.

The ArrayBuffer that you mention is to read a binary buffer, it can be useful for fetching songs or etc... If your API is returning this, I would check out the link to see what you can do. You will most likely be required to decode the buffer and how that is done is completely dependent on how your API is encoding it and I cannot answer that without more detail regarding your API response.

Upvotes: 6

Related Questions