local-weather/components/LocationSearch.tsx
ChrQR 584176baff
All checks were successful
Docker Build & Publish / Build Docker (push) Successful in 1m9s
error handling on wrong input in search bar
2024-05-12 21:58:10 +02:00

43 lines
1.3 KiB
TypeScript

"use client";
import React, { useContext, useState } from "react";
import { getLocation } from "@/app/actions";
import { LocationContext } from "@/context/LocationContext";
export default function LocationSearch() {
const [searchLocation, setSearchLocation] = useState("");
const { 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
className="my-4 w-full rounded h-8 px-2 box-border border-2 hover:shadow-md max-w-md"
id="location"
name="locationSearch"
type="text"
placeholder="Enter a location to get the weather"
value={searchLocation}
onChange={handleChange}
disabled={pending}
aria-label="Enter location to query the weather"
/>
</form>
);
}