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

164
Visualizações
Failing to setState of Functional Component

Assuming the ProfileService API returns an appropriate object, why is the data state variable undefined when I attempt to log it?

NOTE: I am only having this issue in functional components; the same code works in a Class component.

export default function Id() {
  const [data, setData] = useState({});

  useEffect(() => {
    console.log("Mounted.");
    fetchProfile("123");
  }, []);

  const fetchProfile = (id) => {
    ProfileService.getProfile(id).then((response) => {
      if (response.status === 200) {
        setData(response.data);
        console.log("200 OK", data);  // returns "200 OK undefined"
      }
      console.log("Called ", data); // returns "Called undefined"
    });
  };

  return null;
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The setter that is returned from a useState is asynchronous. You won't see the change until the next time your component function is invoked (the change of state will cause that to happen near-immediately)

Of course, you know what the value you just set is...

about 4 years ago · Juan Pablo Isaza Relatório

0

When you tried to get a new state value at once after setting a state, you always will have a previous value.

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