简体   繁体   中英

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. 在此处输入图片说明

and then I get the result. It's ok在此处输入图片说明

But after that I want to use that value. I code this在此处输入图片说明

It shown me the error. 在此处输入图片说明

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM