0

I am trying to save the values of a are you bored API then call it in Final DATA After that i call it it gives me undefind for the first call , then I call it and it gives me undefined then it works fine, how can I fix it?

<section >
<form action="" class="form__wrapper">
    <div class="participants__wrapper">
        <label id="participants__label" for="participants">For how much people the activity:</label>
        <input type="number" id="participants" name="participants">
    </div>
    <div>
        <label for="price-range" id="price-range__label">Your price range:</label>
        <input type="range" name="price-range" id="price-range" min="0" max="1" step="0.1">
    </div>
    <div>
        <button type="submit" id="sumbuit__button">Submit</button>
    </div>
</form>

const howMuchPll = document.querySelector(`#participants`);
const priceRange = document.querySelector(`#price-range`);
const btn = document.querySelector(`#sumbuit__button`);
const form = document.querySelector(`form`);

let valueForPpl = "";
let valueForPriceRange = "";
let FinalDate = [{}];
const boredApiHandler = async () => {
  try {
    const mainData = await fetch(
      `http://www.boredapi.com/api/activity/?participants=${valueForPpl}&price=${valueForPriceRange}`
    );
    const parsedData = await mainData.json();

    return (FinalDate = parsedData);
  } catch {}
};

const howMuchPllHandler = (e) => {
  let inputValue = e.target.value;
  return (valueForPpl = inputValue);
};

const priceRangeHandler = (e) => {
  let priceRangeValue = e.target.value;
  return (valueForPriceRange = priceRangeValue);
};

howMuchPll.addEventListener(`change`, howMuchPllHandler);

priceRange.addEventListener(`change`, priceRangeHandler);

form.addEventListener(`submit`, (e) => {
  e.preventDefault();
  boredApiHandler();
  console.log(FinalDate.activity);
});
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • What about trying the `fetch().then().catch().finally()` promise chain?? As for calling async function in non async function, you need to cover it either with Promise or IIFE https://stackoverflow.com/questions/47227550/using-await-inside-non-async-function – Dhana D. Oct 14 '22 at 07:26

1 Answers1

-1

It's a very common thing in the web developpement.

When you works with API, sometimes the code continues to run even though your program has not had time to retrieve all the information from the API.

To correct this, we use the ASYNC/AWAIT function. It allows you to wait for the API call to finish before continuing.

You have to wait the promise here is a few docs that can helps : promise, async.

It's better for you to understand this and correct it by yourself with the docs I gave you, because you're going to face this problem a lot.

Louis Chopard
  • 334
  • 1
  • 11