the page refreshes automatically after requesting data

193 Views Asked by At

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

There are 1 best solutions below

4
Lugarini On

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"