Skip to content

Commit

Permalink
adding suggestion box
Browse files Browse the repository at this point in the history
  • Loading branch information
naitikagarwal committed Dec 14, 2024
1 parent b406708 commit 5231d4d
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 6 deletions.
8 changes: 6 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import Home from "./components/Home"
import "./App.css"
import Sidebar from "./components/Sidebar"
import { useEffect, useState } from "react"
import { ApiResponse, fetchData } from "./utils/api"
import { ApiResponse, fetchData, fetchSearchData, searchData } from "./utils/api"
const App = () => {
const apiKey = import.meta.env.VITE_API_KEY;
const[searchInput, setSearchInput] = useState("")
const[apiUrl, setApiUrl] = useState(`http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=kharagpur&aqi=no`)
const[apiUrl, setApiUrl] = useState(`http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=ranchi&aqi=no`)
const handleSearch = () => {
if (searchInput) {
setApiUrl(`http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${searchInput}&aqi=no`);
Expand Down Expand Up @@ -51,6 +51,10 @@ const App = () => {
const loadWeatherData = async () => {
try {
const data: ApiResponse = await fetchData(apiUrl);

const searchData: searchData =await fetchSearchData(`https://api.weatherapi.com/v1/search.json?key=${apiKey}&q=ranchi`);
console.log(searchData[0].name);

setWeatherData({
temp_c: data.current.temp_c,
feelslike_c: data.current.feelslike_c,
Expand Down
68 changes: 64 additions & 4 deletions src/components/header.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,55 @@
import './styles/header.css'
import React, { useState } from 'react';
import './styles/header.css';
type Location = {
id?: number;
name: string;
region: string;
country: string;
};
const Header = ({ searchInput, setSearchInput, handleSearch,name }: {
name: string|null;
searchInput: string;
setSearchInput: React.Dispatch<React.SetStateAction<string>>;
handleSearch: () => void;
}) => {
const apiKey = import.meta.env.VITE_API_KEY;
const [suggestions, setSuggestions] = useState<Location[]>([]);
const [loading, setLoading] = useState<boolean>(false);

const fetchSuggestions = async (query: string) => {
try {
setLoading(true); // Start loading
const response = await fetch(
`https://api.weatherapi.com/v1/search.json?key=${apiKey}&q=${query}`
);
const data = await response.json();
setSuggestions(data); // Update suggestions
} catch (error) {
console.error("Error fetching data:", error);
setSuggestions([]); // Clear suggestions on error
} finally {
setLoading(false); // End loading
}
};

const handleFormSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault(); // Prevent page refresh
event.preventDefault();
handleSearch();
};
const handleOptionClick = (location: Location) => {
setSearchInput(location.name); // Update input with selected location
setSuggestions([]); // Clear suggestions
};
const handleInputChange =(e: React.ChangeEvent<HTMLInputElement>)=>{
setSearchInput(e.target.value);
if (e.target.value.trim() === "") {
setSuggestions([]);
return;
}
fetchSuggestions(e.target.value);
};
console.log(suggestions);

return (
<>
<div className="navbar flex flex-row justify-around p-3 bg-stone-300 rounded-bl-2xl shadow-md md:text-2xl text-sm items-center">
Expand All @@ -18,11 +59,30 @@ const Header = ({ searchInput, setSearchInput, handleSearch,name }: {
</div>
<div className="search-bar text-base">
<form action="" className='flex gap-1 items-center ' onSubmit={handleFormSubmit}>
<input type="text" placeholder='Enter City Name' className='p-1 rounded-lg focus:outline-none' value={searchInput} onChange={(e) => setSearchInput(e.target.value)} />
<input type="text" placeholder='Enter City Name' className='p-1 rounded-lg focus:outline-none' value={searchInput}
onChange={handleInputChange} />
{loading && <p style={{ marginTop: "8px" }}>Loading...</p>}
{suggestions.length > 0 && (
<ul style={{listStyle: "none",
padding: 0,
margin: "8px 0 0",
border: "1px solid #ccc",
borderRadius: "4px",
backgroundColor: "white",
position: "absolute",
top:"35px",
zIndex: 1,
}}>
{suggestions.map((location, index) => (
<li key={index} onClick={() => handleOptionClick(location)} className="p-2 cursor-pointer border-b">
{location.name}, {location.region}, {location.country}
</li>
))}
</ul>)}
<button type='submit'><span className="material-symbols-outlined p-1 ">search</span></button>
</form>
</div>
<span className="material-symbols-outlined cursor-pointer">menu</span>
{/* <span className="material-symbols-outlined cursor-pointer">menu</span> */}
</div>
</>
)
Expand Down
22 changes: 22 additions & 0 deletions src/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ export interface ApiResponse {
};
}

export interface searchData {[index: number]:{
id: number,
name: string,
region: string,
country: string,
lat: number,
lon: number,
// "url": "ranchi-jharkhand-india"
}}

export const fetchData = async (apiUrl: string): Promise<ApiResponse> => {
try {
Expand All @@ -34,4 +43,17 @@ export interface ApiResponse {
throw error;
}
};

export const fetchSearchData = async (apiUrl: string): Promise<searchData> => {
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`API error: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
};

0 comments on commit 5231d4d

Please sign in to comment.