I have a bit of JS that is making an API call, getting the value from the that call, and then using that value to set a userReferrer
cookie when the user clicks the submit button on a login form.
<script type="text/javascript">
async function getData() {
const urlValue = parseInt(getUrlParameter('tm'), 10);
const response = await fetch(`/core/nav?productGroupId=${urlValue}`)
const data = await response.json();
return data;
}
const data = getData().then(data => data);
document.getElementById('sign-in-form').addEventListener('submit', function (event, data) {
event.preventDefault();
if (data.ratings) {
createCookie('userReferrer', data.ratings);
}
this.submit();
});
Although I'm passing the data obj to the event listener function, it's undefined
inside the event listener when I try to log it. I can see in the inspector that the call is successfully made and if I log the value outside of the event listener I can see it. Ideas on how I can structure this so the returned API value is properly passed to or obtained within the event listener function?
In order to make sure data
is populated, you need to await
for the Promise that returns from getData
to be resolved.
In other words, you need to make sure your code runs synchronously:
async function useData() {
const data = await getData();
document.getElementById('sign-in-form').addEventListener('submit', function (event) {
event.preventDefault();
if (data.ratings) {
createCookie('userReferrer', data.ratings);
}
this.submit();
});
}
Then you can just call it:
useData();
Note how this function doesn't require await
, since we're not using its result. This means we don't have to wait for it, and it can just finish whenever it's finished doing its thing.
Alternatively, you can write the same code using syntax that's more similar to your original snippet:
getData().then((data) => {
// Inside this scope `data` is already populated
document.getElementById('sign-in-form').addEventListener('submit', function (event) {
event.preventDefault();
if (data.ratings) {
createCookie('userReferrer', data.ratings);
}
this.submit();
});
});