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

191
Vistas
I can't use the value returned from promise

I write the code to fetch data from my api. In the first time I code this.enter image description here

and then I get the result. It's okenter image description here

But after that I want to use that value. I code this enter image description here

It shown me the error. enter image description here

I tried read about promise and async,await a lot but it didn't help me. Please enlighten me.

import logo from "./logo.svg";
import "./App.css";
import React from "react";

function App() {
  const [stateData, setStateData] = React.useState("");
  const testGetData = async () => {
    const data = await fetch("/api/products/test").then((response) => {
      return response;
    });
    return data;
  };
 let productData = [];

 testGetData().then((response)=>{
   return response.json();
 }).then((res)=>{
    productData.push(res);
 });

console.log(productData);
console.log(productData[0].productName);
    
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>{stateData}</p>
      </header>
    </div>
  );
}

export default App;

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

First of all you need to use the state to store the data from the request

Secondly, to get the data, the request needs to be wrapped in a useEffect. You can read more about it here

Here is a good article describing how to get data asynchronously using hooks https://www.robinwieruch.de/react-hooks-fetch-data

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