I want to read data from URL using JavaScript.
below is my code,
function Parent() {
const [data, setData] = React.useState(null);
const url = 'someurl';
React.useEffect(() => {
fetch(url)
.then(res => JSON.stringify(res))
.then(data => setData(data);
});
if (data) {
console.log('data', data);
}
}
logging the data state would give the result like below,
{
"count": 2,
"results": [{
"title": "title1",
"characters": [
"character1",
],
},
{
"title": "title2",
"characters": [
"character3",
],
},
]
}
How can I read results object from URL?
You don't do
fetch(url)
.then(res => JSON.stringify(res))
//...
Instead you do
fetch(url)
.then(res => res.json())
//...
Reason being that res
is a Response
see MDN which contains more than just the data you're interested in (the response body).
simply
fetch(url)
.then(res => res.json())
.then(data => setData(data))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.