I’m working on a webpage with a button. I want to make it so when someone clicks the button, it triggers a call to a REST API. I’m pretty new to this and I’ve been looking all over for help, but I’m still stuck. Can anyone point me in the right direction or give me a simple example of how to do this?
Here’s what I’ve tried so far:
function callApi() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
}
document.getElementById('apiButton').addEventListener('click', callApi);
But I’m not sure if this is the best way or if I’m missing something important. Any tips or advice would be really helpful. Thanks in advance!
Your approach is on the right track. For a more robust implementation, consider using the Axios library. It simplifies HTTP requests and offers better error handling. Here’s an example:
import axios from 'axios';
async function callApi() {
try {
const response = await axios.get('https://api.example.com/data');
console.log(response.data);
} catch (error) {
console.error('Error:', error.message);
}
}
document.getElementById('apiButton').addEventListener('click', callApi);
This method provides cleaner syntax and built-in request/response transformations. Remember to handle API rate limits and add loading indicators for better user experience.
I’ve been in your shoes, and I can tell you that fetch() is a solid choice for API calls. However, I’ve found that adding a timeout can prevent your app from hanging if the API is slow to respond. Here’s a tweak I often use:
function callApi() {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
fetch('https://api.example.com/data', { signal: controller.signal })
.then(response => {
clearTimeout(timeoutId);
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request timed out');
} else {
console.error('Error:', error);
}
});
}
This setup gives you more control over the request and helps prevent potential UI freezes. Just remember to adjust the timeout duration based on your API’s typical response time.
hey there! ur code looks pretty good actually. one thing u might wanna add is some error handling for when the API is down or slow. also, consider using async/await instead of .then() chains - it’s easier to read. good luck with ur project!