简体   繁体   English

如何将获取数据的结果分配给变量? ReactJS

[英]How to assign a result of fetching data to a variable?ReactJS

const storeProducts = fetch('https://yalantis-react-school.herokuapp.com/api/v1/products/').then(res => res.json()).then(res => console.log(res))
const detailProduct = fetch('https://yalantis-react-school.herokuapp.com/api/v1/products/4423b750-48ea-424a-9432-c77261bb4682').then(res => res.json()).then(res => console.log(res))
Object.keys(storeProducts).forEach(item => tempProducts.push({ ...item })
  );
console.log(storeProducts)//returns promise
console.log(detailProduct)//returns promise

const initialState = {
  products: tempProducts,
  productDetails: { ...detailProduct }
};
I'll start with the fact that the app worked fine while the data from the variables included the json from the local file. as soon as the server requests were assigned to the variables, the data stopped loading. ps there are no errors in the console, the console log returns:
''''
// (from console.log outside from fetch)it seems the variables are assigned a promise, not data from the server
Promise {<pending>}__proto__: Promise[[PromiseStatus]]: "resolved"[[PromiseValue]]: undefined
Promise {<pending>}__proto__: Promise[[PromiseStatus]]: "resolved"[[PromiseValue]]: undefined

//console.log(res) of data inside fetch
{items: Array(10)}items: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]__proto__: Object
product.js:14 
{isEditable: false, id: "4423b750-48ea-424a-9432-c77261bb4682", name: "Handcrafted Soft Table", price: 407, origin: "europe", …}

what action should I put the variables storeProducts and detailProduct so that they return data from the server?我应该将变量 storeProducts 和 detailProduct 放在什么位置,以便它们从服务器返回数据?

thnx a lot!!非常感谢!!

You need to await the request until the promise is resolved.您需要await请求,直到承诺得到解决。 After that you can have you output.之后,您可以让您输出。 You can do something like:您可以执行以下操作:

let storeProducts;
let detailProducts;

async function getDetails(){
  storeProducts = await fetch('https://yalantis-react-school.herokuapp.com/api/v1/products/').then(res => res.json());
  detailProduct = await fetch('https://yalantis-react-school.herokuapp.com/api/v1/products/4423b750-48ea-424a-9432-c77261bb4682').then(res => res.json());

  console.log(storeProducts);
  console.log(detailProduct);
}

getDetails();

Hope this works for you.希望这对你有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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