176
rated 0 times
[
179]
[
3]
/ answers: 1 / hits: 10473
/ 5 Years ago, fri, april 12, 2019, 12:00:00
I want to store a Fetch API JSON as a JavaScript object, so I can use it elsewhere. The console.log test works, but I can't access the data.
The Following Works: It shows console entries with three to-do items:
fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => console.log(success));
The Following Does Not Work:
fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => JSON.parse(success));
If I try to access success, it does not contain any data.
Have tried console.log, which works.
Have also tried the following, which works:
fetch('http://localhost:3000/api/todos')
.then(res => res.json())
.then(data => {
let output = '';
data.forEach(function (todo) {
output += `
<ul>
<li>ID: ${todo.id}</li>
<li>Title: ${todo.title}</li>
<li>IsDone: ${todo.isdone}</li>
</ul>
`;
});
document.getElementById('ToDoList').innerHTML = output;
return output;
})
.catch(err => console.log('Something went wrong: ', err));
However, I can't manually update inner HTML; I need the object to do other UX.
More From » json