Design comparison
Solution retrospective
This was my first time working with a json file to pull data from so I learned a lot on that. I had a problem with my JS though where I would like to know if there's a way I could refactor my solution into one single function since there's very little that changes between the three functions I already have. That and any other feedback on the design and functionality is much appreciated! Thanks!
Community feedback
- @Cats-n-coffeePosted almost 2 years ago
Hi Toni!
Nice work! To make your Js less repetitive, you could extract the
fetch
into a separate function. Once you start working with APIs (if you haven't already), you'd want to make sure that you're not duplicating the requests if it isn't really necessary. Some goes here with your Json file. So I would have thefetch
by itself and maybe have the response stored in a global variable (if you use a framework, you'd often store the response in state):let response; async function fetchJson(url) { const response = await fetch(url); const jsonData = await response.json(); response = jsonData; // this places the response in your global variable return jsonData; // the return here might be unecessary since you are placing the response in a variable above, but feel to do this however you want. } fetchJson('data.json');
The example above keeps things simple, however it's strongly recommended to place any
fetch
inside atry
andcatch
when usingasync/await
, so you can handle errors (but data.json is local here). Once you have the response stored in your global variable, you can grab it from inside each daily, week, month function. There are many ways to go about this, if you'd like to keep the promises using.then()
you can replaceasync/await
with that, you'll be assigning the response to your variable inside a.then()
.I have another way in my solution (pretty close to the above), I didn't use a try/catch because it's just a local file. It's quite lengthy because I'm building the card with Js, but if you're interested: https://github.com/Cats-n-coffee/FEM-timeTrackingDashboard/blob/master/src/index.js
Hope this help, let me know if you have questions!
0@ToenShPosted almost 2 years ago@Cats-n-coffee Thanks a lot for taking the time to check it out. Yes its one of my first projects where I'm using APIs and json data files so I'm not really familiar with the best practices just yet but this was really helpful so thanks again!
0 - @catherineisonlinePosted almost 2 years ago
Hey, looks awesome! I would also add some transitions for hover states so it looks smoother
0@ToenShPosted almost 2 years ago@catherineisonline Thank you! I'll see if I can do something about that.
0
Please log in to post a comment
Log in with GitHubJoin 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