1
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!!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can declare variable's outside the function and then reuse them. Answer updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.