Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!