Hello, I have the following issue with this code. When I type a single letter, it doesn’t filter, and consequently, it logs all the elements of the array in the console. However, when I delete the letter, it shows the ones it should have filtered. It’s a strange behavior.
Code Snippet:
const handleCountryFilter = (event) => {
setCountryFilter(event.target.value.toLowerCase());
const regex = new RegExp("^" + newCountryFilter);
const filteredCountries = countries.filter((country) =>
regex.test(country.name.common.toLowerCase())
);
console.log(filteredCountries);
};
Complete code:
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [countries, setCountries] = useState([]);
const [newCountryFilter, setCountryFilter] = useState("");
const hook = () => {
axios
.get("https://restcountries.com/v3.1/all")
.then((response) => setCountries(response.data))
.catch((response) => console.log(`Error: ${response}`));
};
useEffect(hook, []);
const handleCountryFilter = (event) => {
setCountryFilter(event.target.value.toLowerCase());
const regex = new RegExp("^" + newCountryFilter);
const filteredCountries = countries.filter((country) =>
regex.test(country.name.common.toLowerCase())
);
console.log(filteredCountries);
};
return (
<div>
<label htmlFor="txtCountry">find countries</label>
<input
id="txtCountry"
type="text"
value={newCountryFilter}
onChange={handleCountryFilter}
/>
</div>
);
}
export default App;
Thanks!!