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

112
Visualizações
useEffect and undefined

I'm trying to kick off undefined, but I don't understand, what I'm doing wrong. I need to initialize persons without undefinedenter image description here

import { useEffect, useState } from "react";
import { SearchBar } from "./SearchBar";
import { getPersons } from "../../apies/api";
import { ListOfPersons } from "./listOfPersons";
const Home = () => {
    const [valueOfInput, valueOfInputChange] = useState("")
    const [persons, setPersons] = useState()

    useEffect(() => {
        getPersons().then(response => setPersons(response))
    }, [setPersons]); 
    console.log(persons)

    return <div>
       <h1>Поиск персонажей</h1>
       <SearchBar personGetRequest={valueOfInputChange}/> 
       <ListOfPersons personsList={persons}/>
    </div>;
};

export default Home;
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You should initialize the persons with empty array then it will not show undefined. Like the below code

const [persons, setPersons] = useState([])
about 4 years ago · Juan Pablo Isaza Relatório

0

I would suggest you to:

  1. Call the function getPersons only on mount of the component with an empty array in the dependencies array
  2. Inizialize the persons state with an empty array
  3. Be careful about the type of the response of your api (an object with count,next,previous,result fields), in order to call the function setPersons with the result
  4. Take care of errors when call the getPersons api with a catch statement which will set an empty array, for example.
  5. You may would read persons only when persons change instead of every render, so you could put your console.log inside an useEffect with persons array inside the dependencies array.
import { useEffect, useState } from "react";
import { SearchBar } from "./SearchBar";
import { getPersons } from "../../apies/api";
import { ListOfPersons } from "./listOfPersons";
const Home = () => {
    const [valueOfInput, valueOfInputChange] = useState("")
    const [persons, setPersons] = useState([])

    useEffect(() => {
        getPersons()
         .then(response => setPersons(response.data.results))
         .catch(e => setPersons([])
    }, []);

    useEffect(()=>console.log(persons),[persons])

    return <div>
       <h1>Поиск персонажей</h1>
       <SearchBar personGetRequest={valueOfInputChange}/> 
       <ListOfPersons personsList={persons}/>
    </div>;
};

export default Home;
about 4 years ago · Juan Pablo Isaza Relatório

0

You Should use this for fetching data

useEffect(() => {
   getPersons().then(response => setPersons(response.data.data))
}, [setPersons]); 

console.log(persons)
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