I have the following application but I would like to create a conditional that I think is a bit complex and it is the following
If the query has more than 10 matches, I get the following message below the input
Too many matches, specify another filter
If the query has less than 10 matches, show the names of the countries that match
And if you start the application without any letter in the search filter that shows all the countries
This is the code, since it is in react I use CodeSandbox.
Country Filter Application:
import axios from "axios";
import { useState, useEffect } from "react";
const App = () => {
const [countries, setCountries] = useState([]);
const [findCountries, setFindCountries] = useState("");
useEffect(() => {
axios.get("https://restcountries.eu/rest/v2/all").then((response) => {
// console.log(response);
setCountries(response.data);
});
}, []);
const handleFindCountry = (event) => {
setFindCountries(event.target.value);
};
const findCountry = countries.filter((country) =>
country.name.toLowerCase().includes(findCountries.toLowerCase())
);
return (
<div>
<p>
find countries <input onChange={handleFindCountry} />
</p>
<ul>
{findCountry.map((country) => (
<li key={country.alpha2Code}>{country.name}</li>
))}
</ul>
</div>
);
};
export default App;
It's not really too complex, but it would require several changes to your code.
There could be several ways to do it, but I propose this:
We first create a new state called
limitExceded
and initialize it tofalse
.With that state we will define what will be shown on the screen in this way...
Thus, if it
limitExceded
is , it willfalse
print all the countries but if that state has content, then it will show the message that we will put later.Next, we create a new function
findCountry2
that instead of processing the data from the statefindCountries
, will work with an argument that we are going to pass to it. We are going to do that in the functionhandleFindCountry
.Inside said function, as an argument we pass what we write in it
input
and create a new object calledconutriesFound
.And now we can set the limit of results that will be displayed.
If the countries found are less than 10 or 0, or the input is empty, we return
false
tolimitExceded
and update the statefindCountries
. Otherwise,limitExceded
we pass the message "Too many matches, specify another filter" to the state.Making all those changes, all the code would look like this:
Try it on the fork I made of your code.
I clarify that, as I said at the beginning, there are other ways to do this and in fact this way that I offer you may not be the cleanest. But at least it would provide a solution to what you are looking to do.
You should simply validate that the search result is greater than 10 and that the search input has some value.
Tell us if it's what you need :D