Responsive Mobile-First Expense Chart

Solution retrospective
I have no idea how to reference the JSON data file. I tried using parse() and fetch(), but my research was inconclusive. I am submitting with the data stored in a variable in the JS file so I can see how others did it. If anyone has tips about accessing the JSON data from another file, or thoughts in general, let me know!
Please log in to post a comment
Log in with GitHubCommunity feedback
- @ascpenteado
Hi, SweetCaroline36!
Nice job! I think you made it very close to the design.
About reading de JSON file:
You should have gone for the
fetch()
function. The thing is that fetch returns aPromise
and this can make things a little more complex.It would be something like this:
const data = fetch("./data.json") .then((res) => { return res.json(); }) .then((data) => { const amounts = []; data.forEach((x) => { amounts.push(x.amount); }); // ... rest of your code...
Using
.then()
enables you to access the contents of the file. You have to wait until JS reads the file, and then you transform the data from JSON (which is also a Promise) to an object.There is a cleaner way, using
async/await
:async function fetchData() { try { const res = await fetch("./data.json"); const data = await res.json(); return data; } catch (error) { console.error(error); } } const data = await fetchData(); if (data) { const amounts = []; data.forEach((x) => { amounts.push(x.amount); }); // ... rest of your code ...
If you try that I believe that you'll manage to read from the JSON file. :)
If you never heard of Promises or Asynchronous code, there is a lot of good content out there.
Here is one I like: Asynchronous Vs Synchronous Programming
I hope it helps!
Join our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord