Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda