Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
0

You can also use a function like below:



 function doSomething(success){
//do whatever you like
}

fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => doSomething(success));

[#8040] Tuesday, April 9, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynkarinam

Total Points: 740
Total Questions: 103
Total Answers: 103

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
jaylynkarinam questions
Tue, Jul 23, 19, 00:00, 5 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Wed, Oct 31, 18, 00:00, 6 Years ago
Fri, Oct 26, 18, 00:00, 6 Years ago
;