score:338
In order to access the data from a ReadableStream
you need to call one of the conversion methods (docs available here).
As an example:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
// The response is a Response instance.
// You parse the data into a useable format using `.json()`
return response.json();
}).then(function(data) {
// `data` is the parsed version of the JSON returned from the above endpoint.
console.log(data); // { "userId": 1, "id": 1, "title": "...", "body": "..." }
});
EDIT: If your data return type is not JSON or you don't want JSON then use text()
As an example:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(function(response) {
return response.text();
}).then(function(data) {
console.log(data); // this will be a string
});
Hope this helps clear things up.
score:-1
I just had the same problem for over 12 hours before reading next, just in case this helps anyone. When using nextjs inside your _api page you will need to use JSON.stringify(whole-response) and then send it back to your page using res.send(JSON.stringify(whole-response)) and when it's received on the client side you need to translate it back into json format so that it's usable. This can be kinda figured out by reading their serialization section. Hope it helps.
score:4
I dislike the chaining thens. The second then does not have access to status. As stated before 'response.json()' returns a promise. Returning the then result of 'response.json()' in a acts similar to a second then. It has the added bonus of being in scope of the response.
return fetch(url, params).then(response => {
return response.json().then(body => {
if (response.status === 200) {
return body
} else {
throw body
}
})
})
score:11
If you just want the response as text and don't want to convert it into JSON, use https://developer.mozilla.org/en-US/docs/Web/API/Body/text and then then
it to get the actual result of the promise:
fetch('city-market.md')
.then(function(response) {
response.text().then((s) => console.log(s));
});
or
fetch('city-market.md')
.then(function(response) {
return response.text();
})
.then(function(myText) {
console.log(myText);
});
score:13
Note that you can only read a stream once, so in some cases, you may need to clone the response in order to repeatedly read it:
fetch('example.json')
.then(res=>res.clone().json())
.then( json => console.log(json))
fetch('url_that_returns_text')
.then(res=>res.clone().text())
.then( text => console.log(text))
score:19
Little bit late to the party but had some problems with getting something useful out from a ReadableStream
produced from a Odata $batch request using the Sharepoint Framework.
Had similar issues as OP, but the solution in my case was to use a different conversion method than .json()
. In my case .text()
worked like a charm. Some fiddling was however necessary to get some useful JSON from the textfile.
score:37
res.json()
returns a promise. Try ...
res.json().then(body => console.log(body));
score:79
Some people may find an async
example useful:
var response = await fetch("https://httpbin.org/ip");
var body = await response.json(); // .json() is asynchronous and therefore must be awaited
json()
converts the response's body from a ReadableStream
to a json object.
The await
statements must be wrapped in an async
function, however you can run await
statements directly in the console of Chrome (as of version 62).
Source: stackoverflow.com
Related Query
- Retrieve data from a ReadableStream object?
- How to retrieve data from promise object in React JS
- How can I retrieve the data from Promise object in React?
- How to retrieve different type of data from JSON object array and play with it?
- Get object data and target element from onClick event in react js
- How to access data attributes from event object
- React.js: loading JSON data with Fetch API and props from object array
- ReactJS - get json object data from an URL
- React Apollo first object from subscription not being merge into previous data it actually gets removed
- How to retrieve data from firebase in React?
- retrieve data from asyncStorage in react native
- How do I display data from a JSON object using ReactJS?
- How can i get array of object from this data for state and count in reactjs
- How can I extract data from this returned object in an async function?
- How to retrieve data from form using a POST route?
- How to retrieve data from the server using fetch get method and show it in a table
- Display data in a React component from an object where the keys are different but the values are the same
- How can I get the Material-UI DataGrid to read object data from an array?
- How to retrieve data from Redux store using functional components and avoiding useSelector & useDispatch
- Get data from filepond object instance
- How do I retrieve the data from a scanned QR Code?
- How do I correctly add data from multiple endpoints called inside useEffect to the state object using React Hooks and Context API?
- How to retrieve data from date in weather api?
- React iterate over object from json data
- How to retrieve data from custom attribute on option tag in React
- Retrieve data from Apollo store
- Data from the object doesn't convert when using JSON.stringify
- retrieve data from a list of specific IDs in Firebase, follow user and only get their posts
- Client to retrieve data from backend server database table via a websocket connection
- Extract deep down data from JSON Object
More Query from same tag
- How can I connect to api when I use useReducer hook?
- How to stop React Ant Design Upload component from posting files automatically
- RollupJS ES6 module can't get imported because of default not found for redux and redux-form
- Syntax Error - Map multidimensional array in React-Redux
- Multiple videojs players in the same react component
- How to Access package.json data inside the application?
- Redux `connect()` return an object
- Position resets to 0 while using PanGestureHandler from react-native-gesture-handler
- How to redirect on enter press within a component using Redux?
- how to remove the warning "can't perform a react state update on unMounted Component"
- Module not found: Can't resolve 'material-ui/FontIcon'
- How to send data from backend Springboot to client frontend without the use of a Controller?
- How to access object property by variable in Javascript
- Facebook Authentication Firebase with React JS - Providers Error
- How to test arrow function calling in react component with jest?
- React Js SetState is not working, what should be done in my code to fix it
- How to remove eslint Parsing error on ES6 export statement
- React - rendering with moment.js
- Flux / Alt not updating props from store
- ReactJS: propTypes validation for array of objects
- Browserify: Can't seem to get reactify to work with coffeeify
- How do you check a checkbox in react-testing-library?
- an error whilst working with react app - Cannot read property 'photo' of undefined
- Stripe and Firebase: FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
- conditional rendering with toast and usestate does not work with react
- React Router always redirect me to a different url
- set first box clicked as a default at the first load
- React protected route with redux
- can api be called repetitively from react js
- Reactjs req.body shows [object Object]