@Cats-n-coffee
Posted
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 the fetch
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 a try
and catch
when using async/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 replace async/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!
@ToenSh
Posted
@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!