I’ve been working on a project for some time now and I am trying to fetch data from a website, and I want to display that specific data on my site after a user entered a string (in this case a aviation ICAO airport code).
The data I want is: https://aviationweather.gov/api/data/metar?ids=EGLL (the EGLL should be the user input).
In some way or another, I cannot display this on my website. I’ve been trying to test some things out with ChatGPT but without any luck. Can someone help me with my code? Why isn’t it displaying? Please help me understand what I am doing wrong.
My code so far:
import React, { useState } from 'react';
const Metar = () => {
const [metar, setMetar] = useState('');
const [taf, setTaf] = useState('');
const [icaoCode, setIcaoCode] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
fetchMetar(icaoCode);
fetchTaf(icaoCode);
};
const fetchMetar = (code) => {
const metarUrl = `https://aviationweather.gov/api/data/metar?ids=${code}`;
fetch(metarUrl)
.then(response => response.text())
.then(html => {
setMetar(html);
})
.catch(error => {
console.error('Error fetching METAR data:', error);
setMetar('Error fetching METAR data.');
});
};
const fetchTaf = (code) => {
const tafUrl = `https://aviationweather.gov/api/data/taf?ids=${code}`;
fetch(tafUrl)
.then(response => response.text())
.then(html => {
setTaf(html);
})
.catch(error => {
console.error('Error fetching TAF data:', error);
setTaf('Error fetching TAF data.');
});
};
return (
<section className="bg-gray-100 py-8">
<div className="container mx-auto">
<div className="text-center mb-6">
<h1 className="text-4xl font-bold text-gray-800">METAR and TAF Weather</h1>
</div>
<div className="bg-white shadow-md rounded p-6">
<form onSubmit={handleSubmit} className="mb-4">
<div className="flex items-center justify-center">
<input
className="border border-gray-400 rounded py-2 px-4 mr-4"
type="text"
value={icaoCode}
onChange={(e) => setIcaoCode(e.target.value)}
placeholder="ICAO CODE"
maxLength="4"
pattern="^[a-zA-Z0-9]+$"
required
/>
<button className="bg-blue-500 text-white py-2 px-4 rounded" type="submit">
Click here
</button>
</div>
</form>
<div className="text-center">
{metar && <div className="text-lg whitespace-pre-wrap"><strong>METAR:</strong><br /><div dangerouslySetInnerHTML={{ __html: metar }} /></div>}
{taf && <div className="text-lg whitespace-pre-wrap"><strong>TAF:</strong><br /><div dangerouslySetInnerHTML={{ __html: taf }} /></div>}
</div>
</div>
</div>
</section>
);
};
export default Metar;
I hope someone can help me! Thank you so much in advance.