Skip to content

Instantly share code, notes, and snippets.

@rajatjain-21
Last active April 28, 2022 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajatjain-21/e622a3a4c45c2efa05b551b0f349d2e7 to your computer and use it in GitHub Desktop.
Save rajatjain-21/e622a3a4c45c2efa05b551b0f349d2e7 to your computer and use it in GitHub Desktop.
import React, { useState, useCallback } from "react";
import "./styles.css";
import { debounce } from "lodash";
export default function App() {
const [countryName, setCountryName] = useState("");
const [countries, setCountries] = useState([]);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const handleCountryChange = (e) => {
setError("");
setCountryName(e.target.value);
e.target.value && setLoading(true);
setCountries([]);
debounceFetchCountries(e.target.value);
};
const debounceFetchCountries = useCallback(
debounce(async (value) => {
const countries = await fetchCountries(value);
setLoading(false);
setCountries(countries);
}, 1000),
[]
);
const fetchCountries = async (text) => {
if (!text) return [];
const response = await fetch(
`https://restcountries.com/v3.1/name/${text}`
);
const countries = await response.json();
if (countries.length) {
return countries.map((country) => country.name);
}
setError("Couldn't fetch any country this time!");
return [];
};
return (
<div className="App">
<input
value={countryName}
onChange={handleCountryChange}
placeholder="Enter country name"
/>
{loading && <div>Loading...</div>}
{countries.length > 0 && (
<ul className="countryList">
{countries.map((country, index) => (
<li className="country" key={index}>
{country}
</li>
))}
</ul>
)}
<div>{error}</div>
</div>
);
}
.App {
font-family: sans-serif;
text-align: center;
}
input {
padding: 6px;
color: cadetblue;
font-size: 20px;
}
.countryList {
list-style: none;
max-height: 20rem;
overflow-y: auto;
border: 1px solid black;
width: fit-content;
padding: 4px 15px;
margin: 10px auto;
padding: 0;
}
.country {
margin: 8px;
border-bottom: 1px solid black;
color: ;
}
.countryList::-webkit-scrollbar {
-webkit-appearance: none;
}
.countryList::-webkit-scrollbar:vertical {
width: 11px;
}
.countryList::-webkit-scrollbar:horizontal {
height: 11px;
}
.countryList::-webkit-scrollbar-thumb {
border-radius: 8px;
border: 2px solid white; /* should match background, can't be transparent */
background-color: rgba(0, 0, 0, 0.5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment