From 9be06eb77f2de13854a304dbec9c091810625b3f Mon Sep 17 00:00:00 2001 From: sofiahag Date: Wed, 13 Dec 2023 19:51:42 +0100 Subject: [PATCH] add first attempt at autocomplete --- src/components/Weather.jsx | 55 ++++++++++++++++++++++++++++++++------ 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/src/components/Weather.jsx b/src/components/Weather.jsx index bbffa049..dbe00337 100644 --- a/src/components/Weather.jsx +++ b/src/components/Weather.jsx @@ -1,5 +1,6 @@ import React, { useState, useEffect } from 'react'; import { TextField, Button, Typography, Box, ThemeProvider, createTheme } from '@mui/material'; +import Autocomplete from '@mui/material/Autocomplete'; import Lottie from 'lottie-react'; import rain from '../assets/images/rainy.json'; @@ -61,7 +62,7 @@ function Weather() { const [query, setQuery] = useState(''); const [weather, setWeather] = useState({}); const [sky, setSky] = useState('linear-gradient(#799cf2, #b194f5, #f5a793, #f5e994)'); - + const [cityOptions, setCityOptions] = useState([]); const [windowWidth, setWindowWidth] = useState(window.innerWidth); const backgroundStyles = { @@ -122,6 +123,32 @@ function Weather() { } }, [weather]); + useEffect(() => { + const fetchCities = async () => { + try { + if (query.length < 3) { + setCityOptions([]); + return; + } + const response = await fetch(`${api.base}weather?q=${query}&appid=${api.key}`); + const data = await response.json(); + if (response.ok) { + const cityNames = [data.name]; + setCityOptions(cityNames); + } else if (response.status === 404) { + setCityOptions([]); + } else { + console.error('Error fetching cities:', data.message || 'Unknown error'); + setCityOptions([]); + } + } catch (error) { + console.error('Error fetching cities:', error.message || 'Unknown error'); + setCityOptions([]); + } + }; + fetchCities(); + }, [query]); + const search = async () => { try { const response = await fetch(`${api.base}weather?q=${query}&appid=${api.key}&units=metric`); @@ -164,15 +191,27 @@ function Weather() {
- setQuery(newValue)} fullWidth - placeholder="Enter country or city" - onChange={(e) => setQuery(e.target.value)} - value={query} - style={textFieldStyles} + renderInput={(params) => ( + setQuery(e.target.value)} + value={query} + sx={{ + ...textFieldStyles, + '& .MuiAutocomplete-inputRoot .MuiAutocomplete-input': { + width: '100% !important' + } + }} + /> + )} />