简体   繁体   中英

.filter is not a function. Trying to search through names from API data

I'm trying to implement a search filter in this mini-app using the countries API. However, I'm given the error filter is not a function.

Now I think this is because the data has to be an array for the filter() to work. I'm not sure how I would be able to access the data for a search.

Struggling to wrap my head around this one.

Example response.data from my console.log

{data: Array(250), status: 200, statusText: "", headers: {…}, config: {…}, …}
            data: Array(250)
                  [0 … 99]
               0:
            name: "Afghanistan"
  topLevelDomain: [".af"]
      alpha2Code: "AF"
      alpha3Code: "AFG"
    callingCodes: ["93"]
         capital: "Kabul"
    altSpellings: (2) ["AF", "Afġānistān"]
          region: "Asia"
       subregion: "Southern Asia"
      population: 27657145
          latlng: (2) [33, 65]
         demonym: "Afghan"
            area: 652230
            gini: 27.8
       timezones: ["UTC+04:30"]

And here is my filter function that is displaying the error

const Homepage = () => {
  const [countries, setCountries] = useState('');
  const [searchedCountry, setSearchedCountry] = useState('');

  useEffect(() => {
    console.log('effect');
    axios.get(`https://restcountries.eu/rest/v2/all`).then((response) => {
      console.log(response, 'promise fulfiled');
      setCountries(response.data);
    });
  }, []);

  const handleSearch = (event) => {
    setSearchedCountry(event.target.value);
  };

  // Filter function
  const filteredCountries = countries.filter((country) =>
   country.name.toLowerCase().includes(searchedCountry.toLowerCase())
  );

  return (
    <div className='homepage'>
      <input type='text' onChange={handleSearch} />
      <CountryList countries={countries} />
    </div>
  );
};

It would be great to understand this more. Thanks.

Your initial value for countries is in-correct. use same type for default value.

const [countries, setCountries] = useState([]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM