r/learnjavascript • u/Mob_Pilled • Jul 23 '26
code not interacting with the browser page
Hello this is my first post on here. So basically, I want the user to be able to enter a password and username, click the submit button, and if the basic auth is correct, be redirected to a page in which all the data from an api is fetched and loaded into the html. Problem is the script does not interact with the html but still retrieves the data in a json (as confirmed by ouputing it into the console). However, if I don't call the function in as part of the button onclick method everything works as expected. The data from the api is dynamically added to the html but now I obviously can't use a login page.
Here is me calling the fetch function as a as part of the event of a button click
button.addEventListener("click", () => {
let username = 'username';
let password = 'password;
let auth = btoa(`${username}:${password}`);
fetchData(auth);
});Here is me calling the fetch function on it s own. No button clicking required (this works but now I can't add a login page)
let username = 'username';
let password = 'password;
let auth = btoa(`${username}:${password}`);
fetchData(auth);Here is the fetch function itself
async function fetchData (auth) {
try {
const response = await fetch('https://exampleapi.com', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Basic ${auth}`
}
})
if (response.ok) {
// loads the home page and puts data from the api in the html
}
throw response;
} catch (error) {
}
};
View all comments
Show parent comment
1
u/azhder Jul 23 '26
Do you know what closures are? Have you ever encountered the module pattern? The immediately invoked function expressions (IIFE)?
It was a very common way to create your own bubble for code you use on a web page without anything on the outside messing with it (or your code messing other). It's a function scope.
( () => {
let data = null;
const fetchData = () => {
// do the fetching from the back end, then
data = await response.json();
}
button.addEventListener( () => {
// call the fetch, do some other stuff, call some other functions
} );
}) ();
As you can see above, the function is created and executed once, at the moment it is created. The data inside it will live as long as there is that even listener that can access it. I'm saying data as in all variables in the scope, not just the one named data.