local-weather/components/LocationSearch.tsx
2024-05-07 21:18:51 +02:00

44 lines
1.3 KiB
TypeScript

"use client";
import { getLocation } from "@/app/actions";
import { useState } from "react";
import { useFormStatus } from "react-dom";
export default function LocationSearch(props: any) {
const [searchLocation, setSearchLocation] = useState("");
const setGeoLocation = props.setGeoLocation;
const { pending } = useFormStatus();
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchLocation(e.target.value);
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
try {
const coordinates = await getLocation(searchLocation);
setGeoLocation(coordinates);
} catch (error) {
console.error("Error fetching location:", error);
}
};
return (
<>
<form onSubmit={handleSubmit}>
<input
id="location"
name="locationSearch"
type="text"
placeholder="enter a location to get the weather"
value={searchLocation}
onChange={handleChange}
/>
<button type="submit" disabled={pending}>
{pending ? "Searching..." : "Search"}
</button>
<label htmlFor="location" className="hidden">
Enter location to get the weather!
</label>
</form>
</>
);
}