Vicky Pawar
Vicky Pawar

Reputation: 45

how to reload windows with url update in javascript

i have three buttons so when i click on button1 then that button function call and store the string value to the Endpoint and windows should reload with updated data.. so the updated url should be https://api_url_here/national

but the problem is windows is not relaoding with updated value

var btn1 = document.querySelector(".btn1");
var endpoint = [];
console.log(endpoint);
fetch(`https://api_url_here/${endpoint}`)
  .then((response) => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error("Something went wrong");
    }
  })
  .then((newsData) => {
   console.log(newsData);
    })

btn1.addEventListener("click", function () {
    endpoint = "national";
    console.log(endpoint);
});
        <div class="menu">
          <button class="btn1">national</button>
          <button class="btn2">buisness</button>
          <button class="btn3">politics</button>
        </div>

Upvotes: 0

Views: 46

Answers (2)

Ayush Walia
Ayush Walia

Reputation: 172

Need to use querySelectorAll to get all buttons and bind event to each one of them:

var buttons = document.querySelectorAll(".menu-button");
function fetchData(endpoint) {
    fetch(`https://api_url_here/${endpoint}`).then((response) => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error("Something went wrong");
        }
    })
    .then((newsData) => {
        console.log(newsData);
    });
}

buttons.forEach(b => b.addEventListener("click", function (event) {
    fetchData(event.target.getAttribute("data-value"));
}));

HTML:

<div class="menu"> 
    <button class="menu-button" data-value="national">national</button> 
    <button class="menu-button" data-value="business">business</button> 
    <button class="menu-button" data-value="politics">politics</button> 
</div>

Upvotes: 1

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

You should call your API after button click. Currently, it's being called before that happens.

I suggest wrapping the fetch() call in a function to make your code more universal. Also, you can attach an event to all of your buttons and call the new function like this:

var btn1 = document.querySelectorAll(".btn1");

btn1.forEach(function (btn) {
  btn.addEventListener("click", function (e) {
    callAPI(e.target.value);
  });
});

function callAPI(endpoint) {
  fetch(`https://api_url_here/${endpoint}`)
  .then((response) => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error("Something went wrong");
    }
  })
  .then((newsData) => {
   console.log(newsData);
  })
}
<div class="menu">
          <button class="btn1" value="national">national</button>
          <button class="btn1" value="business">buisness</button>
          <button class="btn1" value="politics">politics</button>
        </div>

Upvotes: 1

Related Questions