Search code examples
jsontypescriptapiasync-awaitgithub-api

Page Reloads On Fetching API


I'm currently working on Github user API, and I want test how things works before moving on project but, I go one issue

const btn = document.querySelector('button') as HTMLButtonElement
const input = document.querySelector('input') as HTMLInputElement

const  USER_API: string = 'https://api.github.com/users/callmenikk'

const fetchData = async () => {
    const fetchUser = await fetch(USER_API)
    const userData = fetchUser.json()
    userData.then(resolve => console.log(resolve))
}

btn.addEventListener('click', fetchData)

with this function I want to output my personal user data in console but, it reloads page and puts question mark in ending of link like that http://localhost:3000/? without outputing my JSON in console, but without EventListner to put this function outside, it works well. what am I doing wrongly?


Solution

  • I guest type of your btn (html attribute type) is submit, then when you click the button, a form will be submitted. That action reloads your page.

    To fix that issue, you can remove the button type, or ignore submit event in the event handler function.

    const fetchData = async (event) => { // event parameter
        event.preventDefault(); // ignore event
        const fetchUser = await fetch(USER_API)
        const userData = fetchUser.json()
        userData.then(resolve => console.log(resolve))
    }