@chriscodes17
Posted
Well done on the design and getting it matching! The app functions well and the user experience is also good.
Looking at your index.js code, there is a lot of repeating code for when you are fetching. What I recommend to do in this situation is to create a function for fetching and creating a function for rendering the advice data. These functions will handle all your fetching and adding the necessary data to the DOM. It can look something like this:
const fetchAdvice = () => {
fetch('https://api.adviceslip.com/advice')
.then((response) => {
return response.json();
})
.then((data) => {
return render(data);
})
.catch(function (error) {
console.log('Error fetching advice:', error);
});
};
const render = (data) => {
document.getElementById('advice-content').innerHTML = data.slip.advice;
document.getElementById('advice-number').innerHTML = data.slip.id;
};
document.getElementById("advice-button").addEventListener("click", fetchAdvice)
fetchAdvice() //called on initial page render
As you can see with both the functions, there is more organization of code and it makes the code reusable with using those functions. This is just a tip on how to make your code more reusable and it will come in handy when you are dealing with large amounts of data or specific functionalities that an app requires.
Good job overall!
Marked as helpful
@Jazzy486
Posted
@chriscodes17 Yup, the js code is definitely redundant, will work on that. Thanks for the suggested solution.