Reputation: 61
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?
thnx a lot!!
Upvotes: 1
Views: 1522
Reputation: 4748
You need to await
the request until the promise is resolved. 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.
Upvotes: 1