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

110
Visualizações
React setState don't update values inside a promise

I'm trying to store data with my setState method inside my function but it never update it, however if I set them to a variable (I call it "x") it works.

I have my function which returns a Promise

I hope I can get help figuring out where I went wrong or understand if it cannot be done or not.

import { NextPage } from "next";
import { useState } from "react";
import { useAirtable } from "../functions/useAirtable";
import { MyType } from "../model/MyType";

const Foo: NextPage = () => {

  const [barbaz, setBarbaz] = useState<any>([]);
  let x: any = [];

  try {
    useAirtable("My_Table").then((data: MyType) => {

        setBarbaz(data);
        x = data;

        console.log("print1: ", data); //It PRINTS data
        console.log("print2: ", barbaz); //It PRINTS empty array
        console.log("print3: ", x); //It PRINTS data
      }
    );
  } catch (error) {}

  console.log("print4: ", barbaz); //It PRINTS empty array
  console.log("print5: ", x); //It PRINTS empty array

  return <div> where is waldo </div>;
};

export default Foo;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Wrap your async call on a useEffect hook.

import { NextPage } from "next";
import { useState, useEffect } from "react";
import { useAirtable } from "../functions/useAirtable";
import { MyType } from "../model/MyType";

const Foo: NextPage = () => {

  const [barbaz, setBarbaz] = useState<any>([]);
  
  useEffect(() => {
    useAirtable("My_Table").then((data: MyType) => {
      setBarbaz(data);
    }
  }, [])

  return <div> where is waldo </div>;
};

export default Foo;
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