local-weather/components/LocationSearch.tsx

46 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-05-05 20:55:51 +00:00
"use client";
import React, { useContext, useState } from "react";
2024-05-05 20:55:51 +00:00
import { getLocation } from "@/app/actions";
import { LocationContext } from "@/app/page";
2024-05-04 21:04:30 +00:00
export default function LocationSearch() {
const [searchLocation, setSearchLocation] = useState("");
const { geoLocation, setGeoLocation } = useContext(LocationContext);
const [pending, setPending] = useState(false);
2024-05-05 20:55:51 +00:00
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchLocation(e.target.value);
};
2024-05-07 19:18:51 +00:00
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setPending(true);
2024-05-07 19:18:51 +00:00
try {
const coordinates = await getLocation(searchLocation);
setGeoLocation(coordinates);
} catch (error) {
console.error("Error fetching location:", error);
}
setPending(false);
2024-05-05 20:55:51 +00:00
};
2024-05-07 19:18:51 +00:00
2024-05-04 21:04:30 +00:00
return (
<form onSubmit={handleSubmit}>
<input
id="location"
name="locationSearch"
type="text"
placeholder="Enter a location to get the weather"
value={searchLocation}
onChange={handleChange}
disabled={pending}
/>
<button type="submit" disabled={pending}>
{pending ? "Searching..." : "Search"}
</button>
<label htmlFor="location" className="hidden">
Enter location to get the weather!
</label>
</form>
2024-05-04 21:04:30 +00:00
);
}