46 lines
1.3 KiB
TypeScript
46 lines
1.3 KiB
TypeScript
"use client";
|
|
import React, { useContext, useState } from "react";
|
|
import { getLocation } from "@/app/actions";
|
|
import { LocationContext } from "@/app/page";
|
|
|
|
export default function LocationSearch() {
|
|
const [searchLocation, setSearchLocation] = useState("");
|
|
const { geoLocation, setGeoLocation } = useContext(LocationContext);
|
|
const [pending, setPending] = useState(false);
|
|
|
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
setSearchLocation(e.target.value);
|
|
};
|
|
|
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
setPending(true);
|
|
try {
|
|
const coordinates = await getLocation(searchLocation);
|
|
setGeoLocation(coordinates);
|
|
} catch (error) {
|
|
console.error("Error fetching location:", error);
|
|
}
|
|
setPending(false);
|
|
};
|
|
|
|
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>
|
|
);
|
|
} |