Results Summary Component with JavaScript and Fetch API (JSON)
Design comparison
Solution retrospective
What I have learned:
I have created the entire colored button container with all its elements using JavaScript and retrieved the data from the JSON file using the Fetch API with asynchronous code. For the styling of the elements I used CSS.
I've learned how to create elements and set classes with JavaScript. Also I've learned how to fetch data from JSON and how to implement this data in newly created elements.
My questions to the community:
My JavaSript solution for creating the colored button container with its elements and fetching the data from the JSON file is quite long.
What do you think about it? Is my solution ok? Do you have suggestions for improving the code? Is there a better or simpler approach?
I am very happy about any advice!
Best regards Thomas
Community feedback
- @markuslewinPosted over 1 year ago
One way to make the code simpler would be to first fetch the data, and then create the elements by iterating over the fetched array.
That way, the data is fetched only once, and you don't have to repeat the logic for creating elements for each category.
const getData = async () => { const response = await fetch("./scripts/data.json"); const jsResponse = await response.json(); return jsResponse; }; getData().then((data) => { // Get Parent Container const parentContainer = document.querySelector(".container-actions"); data.forEach((result) => { // create buttons, etc }); });
If you want a more declarative approach to creating the elements, you could write a
<template>
in the HTML, and then clone that template with JS. See <template>: The Content Template element.Marked as helpful0
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