0

I was trying to request some data using axios and then log that data into the console, however once the try statement is executed the data is loged into the console but the page refreshes immediately and the console becomes empty again without returning any error. Does anyone have an idea why this is happening?? I don't know if it is relevant or not but I'm using ES6 modules and webpack.

const searchbar = document.querySelector('.searchbar');
const searchBtn = document.querySelector('.search-btn');

searchBtn.addEventListener('click', async () => {
  const searchTerm = searchbar.value;
  try {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${searchTerm}&appid=*********`);

    const { lat } = response.data.coord;
    const { lon } = response.data.coord;
    const cityName = response.data.name;
    console.log({ lat, lon, cityName });
  } catch (err) {
    alert(`${err} from getLocation`);
    return undefined;
  }
});
  • What kind of element is `searchBtn`? If it's a submit button, clicking it will submit the form and reload the page, unless you call `event.preventDefault()` in the listener function. – Barmar Sep 20 '22 at 16:56
  • `searchBtn` is most likely a submit button in a form and you're not stopping that submit button from doing its job - submit a form. – Andreas Sep 20 '22 at 16:56

1 Answers1

0

Check if your button searchBtn is inside a form and if the button is submit type. If so, when you click the button you submit the form and the page refreshes.

If you want to the the console output, go to console settings and check the option "Preserve log upon navigation"

Lugarini
  • 792
  • 5
  • 11
  • 32