Skip to content

Commit

Permalink
add first attempt at autocomplete
Browse files Browse the repository at this point in the history
  • Loading branch information
sofiahag committed Dec 13, 2023
1 parent cd4b8e9 commit 9be06eb
Showing 1 changed file with 47 additions and 8 deletions.
55 changes: 47 additions & 8 deletions src/components/Weather.jsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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`);
Expand Down Expand Up @@ -164,15 +191,27 @@ function Weather() {
</Typography>
<Box mt={3} display="flex" justifyContent="center">
<form onSubmit={handleSubmit}>
<TextField
<Autocomplete
id="search"
type="text"
variant="outlined"
options={cityOptions}
value={cityOptions.includes(query) ? query : null}
onChange={(event, newValue) => setQuery(newValue)}
fullWidth
placeholder="Enter country or city"
onChange={(e) => setQuery(e.target.value)}
value={query}
style={textFieldStyles}
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
placeholder="Enter country or city"
onChange={(e) => setQuery(e.target.value)}
value={query}
sx={{
...textFieldStyles,
'& .MuiAutocomplete-inputRoot .MuiAutocomplete-input': {
width: '100% !important'
}
}}
/>
)}
/>
<Button type="submit" variant="contained" color="primary" fullWidth style={buttonStyles}>
<Typography variant="button" style={{ fontSize: '1.1rem' }}>Search</Typography>
Expand Down

0 comments on commit 9be06eb

Please sign in to comment.