Filtering Issue in React: Odd Behavior When Typing Single Letters

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!!

const handleCountryFilter = (event) => {
  const filterValue = event.target.value.toLowerCase();
  setCountryFilter(filterValue);
  const regex = new RegExp("^" + filterValue);
  const filteredCountries = countries.filter((country) =>
    regex.test(country.name.common.toLowerCase())
  );
  console.log(filteredCountries);
};

use the event.target.value directly to create the regular expression

1 Like

It worked, thank you very much! Could you explain to me why it works this way? I don’t understand, thank you very much!!

1 Like

Setting the filterValue first and then using it in the regex and the countries.filter function, you ensure that the updated filter value is used for filtering.

Because you can’t use a state variable right after setting it. It will be the initial value until the next render. In the next render, you have access to the new state value inside the component.

function App() {
  const [count, setCount] = useState(0);
  const [behind, setBehind] = useState(0);

  function handelButtonClick() {
    setCount(count => count + 1)
    setBehind(count)
  }

  return (
    <button onClick={handelButtonClick}>
      count is {count} {' '} behind is {behind}
    </button>
  );
}

export default App;
1 Like

Thank you very much!!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.