0

I am trying to set the data that I get from the fetch to start my timer.

fetch("https://fakestoreapi.com/products")
.then((data)=>{
  return data.json();

  // console.log(data);
}).then((completedata)=>{
  console.log(completedata[2].price);
  let timeOne = completedata[2].price;
  // console.log(timeOne)
  document.getElementById("total-time-1").innerHTML=completedata[2].price + "H";
});

I want to use the returned 55.99 number as the set value for the first item and then use different values for the other 11 remaning pegs:

let timeOne = completedata[2].price; 

const allPegs = [
  createPeg('peg-1', timeOne * 60), //  6 seconds
  createPeg('peg-2', 0.05 * 60), //  6 seconds
  createPeg('peg-3', 60 * 60), // 10 seconds
  createPeg('peg-4', 300 * 60), // 300 minutes
  createPeg('peg-5', 5 * 60),
  createPeg('peg-6', 60 * 60),
  createPeg('peg-7', 15 * 60),
  createPeg('peg-8', 20 * 60),
  createPeg('peg-9', 30 * 60),
  createPeg('peg-10', 90 * 60),
  createPeg('peg-11',60 * 60),
  createPeg('peg-12', 70 * 60), // 70 minutes.
]; 

Is there any way to access the data outside of the fetch? so far I get this error message:

Uncaught ReferenceError: completedata is not defined

Jhona
  • 49
  • 9
  • 2
    that's because `completedata` is only defined inside `.then((completedata)` callback - you could `return completedata` in that last `.then` ... and then that promise chain will return a Promise that resolves to `completedata` - but you haven't shown how that fetch is at all related to the rest of the code, so ... can't help more than that – Jaromanda X Aug 15 '22 at 11:14
  • You could wrap all this logic inside a separate function. – AdityaParab Aug 15 '22 at 11:16
  • or run the code that depends on `completedata` inside the `.then((completedata)` block – Jaromanda X Aug 15 '22 at 11:16

0 Answers0