Design comparison
Solution retrospective
I'm proud to have managed to carry out an exercise involving API.
What challenges did you encounter, and how did you overcome them?I had difficulty getting the api to replace the text in the HTML, after many attempts I managed to perform this action.
What specific areas of your project would you like help with?I would like to receive tips on how to work with the API, as it is an area that I recently started studying.
Community feedback
- @0xabdulkhaliqPosted 6 months ago
Hello there 👋. Congratulations on successfully completing the challenge! 🎉
- I have a suggestion regarding your code that I believe will be of great interest to you.
LET'S REFACTOR YOUR SCRIPT 🟡:
- Currently you have utilized promises to fetch api right ? Instead you can try using
async
/await
which helps you to write a more cleaner and well structured code.
- Here's the refactored code,
let buttonUpdate = document.querySelector('.advice-update'); let adviceId = document.getElementsByClassName('advice-id')[0]; let advicePhrase = document.getElementsByClassName('advice-phrase')[0]; const apiUrl = 'https://api.adviceslip.com/advice'; // Helper function to handle API fetch async function fetchAdvice() { try { const response = await fetch(apiUrl); if (!response.ok) { throw new Error(`Error getting data from API: ${response.status}`); } const data = await response.json(); return data['slip']; } catch (error) { console.error(`Error in API request: ${error}`); } } // Event listener for button click buttonUpdate.addEventListener('click', async function() { const advice = await fetchAdvice(); if (advice) { // Update the advice phrase and ID advicePhrase.innerHTML = advice.advice; adviceId.innerHTML = `ADVICE #${advice.id}`; } });
- The updated code is more readable and easier to follow compared to the callback-based approach.
- Errors can be handled using try/catch blocks, making it easier to manage exceptions. The asynchronous operations are more sequential and straightforward, avoiding the "callback hell" issue, and finally now your code is more maintainable and easier to reason to read.
.
I hope you find this helpful 😄 Above all, the solution you submitted is great !
Happy coding!
Marked as helpful0@yuriownPosted 6 months ago@0xabdulkhalid Thank you very much for the suggestion, I'm going to study this subject, it's all very new to me!
0@0xabdulkhaliqPosted 6 months agoYou're welcome @yuriown !
Additionally, i would recommend Asynchronous JavaScript learning module from MDN. It's a great resource. You can familiar with some lessons but it's good to refresh the concepts you learned once again!
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