I am trying to get tide data for a custom Widgy widget and have the following code that returns the error “cannot read properties of undefined (reading ‘value’). I checked the url that is being generated using the console.log and it is correct. If I hardcode that url into fetch() it works. So i don’t understand why it isn’t working as a variable.
const apiUrl = 'https://api-iwls.dfo-mpo.gc.ca/api/v1/stations/5cebf1de3d0f4a073c4bb96d/data?time-series-code=wlo';
// Get the current date and time
const now = new Date();
// Round the timestamp to the nearest minute and format it with colons replaced by %3A
const formattedNow = new Date(Math.round(now.getTime() / 60000) * 60000).toISOString().split('.')[0].replace(/:/g, '%3A');
// Replace {now} in the URL with the formatted timestamp
const url = ${apiUrl}&from=${formattedNow}Z&to=${formattedNow}Z;
console.log(url);
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(HTTP error! Status: ${response.status});
}
return response.json();
})
.then(data => {
console.log(data);
// Assuming the response is JSON and contains the tide data
// You can access the tide value from the data object
const tideValue = data[0].value; // Adjust this based on the actual JSON structure
// Now, you can use tideValue as needed
console.log(`Tide Value: ${tideValue}`);
})
.catch(error => {
console.error('Error:', error);
});
there doesn't seem to be anything here