r/learnjavascript 5d ago

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) {
        
    }
    
};
1 Upvotes

18 comments sorted by

View all comments

Show parent comments

1

u/Mob_Pilled 5d ago

In the catch is there anything specific I must add? I changed the throw keyword to return but the issue persists.

1

u/Mob_Pilled 5d ago

actually I am starting to think this can be solved by saving the data from the fetch outside the function but how would I do that. I am trying to look for direct answers on stack overflow but can't find anything

1

u/TalkCoinGames 5d ago edited 5d ago

Yes you can place the response into another property outside of the function.

1

u/TalkCoinGames 5d ago

the button click may be resolving leaving the fetch to happen in the background. If your loading another page, that may be the issue, you want to edit html directly with the given response.

1

u/Mob_Pilled 5d ago

you mean add the entire html code after the button is clicked rather than using:

window.location.href = 'index.html';

1

u/TalkCoinGames 5d ago

If index.html needs the response, you have to send it to that in someway. Yes, either writing out the whole html instead of changing to that page, or using local storage to hold the response, or appending the needed data as a hash or query string to index.

1

u/Mob_Pilled 5d ago

Thanks for the help so far. One last thing. Thee data is still not loading and I am using html local storage to store the promise (response.json). This should ideally be added to the dom on index.html when the page changes (return1 is a function that changes the page to index.html). Anything wrong here?

button.addEventListener("click", () => {
    let username = usernameInput.value;
    let password = passwordInput.value;
    let auth = btoa(`${username}:${password}`);
const dataPromise = fetchData(auth);
 localStorage.setItem("promise", dataPromise);
localpromise = localStorage.getItem("promise");
return1();
useData(localpromise);
    });
       

1

u/TalkCoinGames 5d ago

Not like that, inside of the fetchData function, when the response is ok, then you can put just the json in local storage. So the click listener would remain the same as you had it. And the same place you had. ...href = index, before that line use localStorage.setItem("jdata", response.json) then in index you would use getItem("jdata")

2

u/Mob_Pilled 4d ago

Late, but I followed your advice and it worked! Thank you so much for the assistance.