Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
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>
    </>
  );
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
    </>
  );
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda