I am using Openweather API , to fetch data like units, weather report, etc. I am trying to create a toggle where the temp changes on clicking as per the toggle button.Like Celsius to Kelvin,etc.
In below code I am trying to pass units to url and using SegmentedControl(it is a react component package)to use the toggle UI.But the value (value: “standard”,etc) that I am using is not able to pass in the units of the url (const url = `https://api.openw…..) .I am not able to figure out how I can pass the value to the units in the URL so that temperature changes automatically without going through any mathematical equations. .
I have omitted some of the code lines for better visibility .
export default function Home() {
const [weather, setWeather] = useState("");
const [city, setCity] = useState("");
const [units, setUnits] = useState();
const apiCall = async (e) => {
e.preventDefault();
const loc = e.target.elements.loc.value;
const url = `https://api.openweathermap.org/data/2.5/weather?q=${loc}&appid=${apiKey}&units=${units}`;
const req = axios.get(url);
const res = await req;
setWeather({
descp: res.data.weather[0].description,
temp: res.data.main.temp,
city: res.data.name,
humidity: res.data.main.humidity,
wind: res.data.wind.speed,
feel: res.data.main.feels_like,
});
setCity(res.data.name);
};
const Weath = () => {
return (
<div className="container">
{" "}
<div>
<div>
<Text mr="xs">Units:</Text>
<SegmentedControl
value={units}
onChange={setUnits}
data={[
{
value: "standard",
label: (
<Center>
<Box>Kelvin</Box>
</Center>
),
},
{
value: "metric",
label: (
<Center>
<Box>Celsius</Box>
</Center>
),
},
{
value: "imperial",
label: (
<Center>
<Box>Fahrenheit</Box>
</Center>
),
},
]}
/>
</div>
</div>
<div className="top">
<div className="text-left">
<div className="flex gap-2">
<p className="text-2xl ">{weather.city}</p>
<CiLocationOn size={25} />
</div>
<div className="text-7xl font-bold">
{weather.temp}
</div>
</div>
</div>
.
.
.
</div>
);
};
return (
<div className="app">
<div className="search">
<form onSubmit={apiCall}>
<input type="text" placeholder="city" name="loc" />
<button className="bttn">Search</button>
</form>
{weather && <Weath />}
</div>
</div>
);
}
I am expecting to change the temperature as per the given option/toggle.