Design comparison
Solution retrospective
This was my first time using an api call in javascript. I should point point out that I've only been learning and using js going on two months now, so I have limited experience with some aspects of it especially with asynchronous functions.
I tried to implement some sort of feedback to the user when the api call fails due to bad network. I was able to get it working (sort of). If you tried to generate an advice without a connection you'd see what I did. The issue is. I wanted to be able to make the api call retry a couple of times before giving that feedback; right now it just gives the error once it fails the first time. Tried to research some solutions online but some persons were using 'Promises' which I frankly don't understand well at this point. If you know a way I could do something like that or you can point me to a good resource to learn about promises, I'd be very grateful. Thanks in advance
Community feedback
- @IamparvesPosted 9 months ago
You can implement a retry system like the below function and use that
async function retryGetAdvice(retries = 3, retryDelay = 2, err = null) { if (!retries) { return Promise.reject(err); } return fetch(apiUrl, { method: "GET" }).catch(async (error) => { if (retryDelay) { await new Promise((resolve) => setTimeout(resolve, retryDelay * 1000)); } return retryGetAdvice(retries - 1, retryDelay, error); }); }
By default it will retry 3 times after every 2 seconds. You can change that when retryGetAdvice function is being called inside getAdvice function.
You can find the full script.js file here: Script.js Gist
One other thing I want to mention is that, I noticed for the loading effect you used a fixed timeout. I don't think that's a ideal solution. Because not every requests will take 1.5 seconds, right? You should try to fix that.
Hope this helps :)
Marked as helpful0@UzomaFidelisPosted 9 months agoYh, I tried to make it only last as long as the request but on a good connection, the loader barely shows. I'll try to make it wait for the request to succeed or fail, then maybe a little extra delay for when it succeeds very quickly. Also, wouldn't want a user spamming the button, that why I had to implement that loading downtime when the button is disabled. Thanks for your suggestions. Will try them out and update this solution soon @Iamparves
PS: Thanks to your code and some more reading and trying, I've been able to get this working much better than before. Tell me what you think of it now. If you have the time
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