'Array length doesn't change

i've got a problem. I'm trying to make data search from API. The problem is that {people.length === 0 && <p>No data</p>} is not working. When i console.log people.length the length value doesn't change when i'm typing. Where's the problem?

Here's my code:

const PeopleSearch = () => {
  const [people, setPeople] = useState([]);
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    const fetchData = async () => {
      const response = await axios.get(swapi);
      const transformedPeople = response.data.results.sort((a, b) =>
        a.name.localeCompare(b.name)
      );
      setPeople(transformedPeople);
      setLoading(false);
    };

    fetchData();
  }, []);

  const searchHandler = (event) => {
    setSearch(event.target.value);
  };

  return (
    <>
      <Input
        type="text"
        placeholder="Search by name..."
        onChange={searchHandler}
      />
      <section>
        {loading ? (
          <Loading />
        ) : (
          <PeopleList
            people={people.filter(({ name }) => {
              if (name.toLowerCase().includes(search.toLowerCase())) {
                return people;
              }
            })}
          />
        )}
        {people.length === 0 && <p>No data</p>}
      </section>
    </>
  );
};


Solution 1:[1]

You're only calling setPeople once, on mount, with the useEffect(() => { ... }, []) - so people.length will remain the same once the API call completes. You need to use the filtered array both for the PeopleList prop and the No data check.

You should also tweak your filter, since it only cares about whether its return value is truthy or not.

const filteredPeople = people.filter(({ name }) => name.toLowerCase().includes(search.toLowerCase()));
return (
    <>
      <Input
        type="text"
        placeholder="Search by name..."
        onChange={searchHandler}
      />
      <section>
        {loading ? (
          <Loading />
        ) : (
          <PeopleList
            people={filteredPeople}
          />
        )}
        {filteredPeople.length === 0 && !loading && <p>No data</p>}
      </section>
    </>
  );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance