When retrieving API data, the page refreshes automatically

Currently experimenting with the Github user API to understand how things function before incorporating it into a project. However, I've encountered an 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 code snippet, my goal is to display my personal user data in the console. However, when executed, it reloads the page and adds a question mark at the end of the link such as http://localhost:3000/?. The JSON output is not displayed in the console. Strangely, if I remove the EventListener, the function works correctly. What could I be doing incorrectly?

Answer №1

It appears that the type of your button element, specifically the `btn` attribute in HTML, is set to 'submit'. This means that when you click on the button, a form submission will occur and your page will be reloaded as a result.

To resolve this issue, you have a couple of options: either remove the submit type from the button, or handle the submit event in your event handler function by ignoring it.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Peeling back the layers of Jackson - revealing the object within

When I receive server responses, they often come wrapped with additional information. For instance: { "response_a" : ..., "some_metadata" : 1234, "more_metadata" : abcd } or { "response_b" : [...], "some_meta ...

Jackson FasterXML: there are no required methods for utilizing the @JsonView feature

When converting a java-object to a json-string, I am trying to organize the dynamic @JsonIgnore property. In one example, it is achieved as follows: for (codehause jackson) ObjectMapper oMapper = new ObjectMapper(); oMapper.setSerializationConfig(... In a ...

The functionality of the back button in a JavaScript website only allows users to navigate through their browsing

I'm currently experiencing an issue with the back navigation button on my one-page website. When I load a new page, I use the following code snippet: displayPage = function (page, json) { var stateObj = { "page": page, 'json': j ...

Tips for preventing <v-layouts> from impacting one another

I'm currently working on a dynamic link box for a homepage website, which can be viewed at . Inside this link box, I have included a button that allows the creation of buttons that function as links. Interestingly, the layouts of both the options but ...

Is it possible to use a PHP array as a JSON-encoded object for a select field value and interact with it using JavaScript?

I have a PHP function that retrieves database values to populate a select form field. I am attempting to fill the option elements with all relevant data from the query (id, name, min, max) without needing an AJAX request. To achieve this, I decided to json ...

Encountered an error while trying to read package.json file: npm install

After entering the command "$npm install," I'm having trouble getting package.json to parse correctly. My NPM version is v2.11.2, running on ubuntu 14.04. Here is my package.json: { "name": "sockjs-express", "version": "0.0.0-unreleasable", ...

Ways of invoking a component method from a service in Angular 2

I have a concept for creating a unique service that is capable of interacting with one specific component. In my application, all other components should have the ability to call upon this service and then have it interact with the designated component in ...

Discovering objects nested within other objects

I am currently attempting to locate a specific element within another element. The structure of my HTML looks like this: <div> <label>test</label> <div> <a>testlink</a> <input type=&apos ...

What is Prettier's reasoning for suggesting the use of `;` before a destructuring assignment declaration?

I am facing an issue with the if block within my Angular component: if (desc.length > 0) { [this.errorMsg] = desc } The problem arises as Prettier suggests adding a ; at the start of the destructuring assignment: if (desc.length > 0) { ;[thi ...

Encountering errors in Typescript build due to issues in the node_modules directory

While running a typescript build, I encountered errors in the node_modules folder. Despite having it listed in the exclude section of my tsconfig.json file, the errors persist. What's puzzling is that another project with identical gulpfile.js, tsconf ...

How can I display data both as a dropdown and an autocomplete in Angular using a textbox?

There is a textbox with autocomplete functionality. When the user clicks on the textbox, an API call is made with two parameters - Pubid and Date. The data is then displayed in a dropdown with autocomplete feature. Now I am attempting to have the data app ...

Extract and loop through JSON data containing various headers

Having no issues iterating through a simple JSON loop, however, the API I am currently utilizing returns a response with multiple headers. Despite my efforts in various methods to access the results objects, I still face some challenges. The response struc ...

Guide to accessing a menu through Long press or Right click in Angular2

I recently started experimenting with angular 2 and I am trying to figure out how to create a menu that opens with multiple options on both mobile and desktop devices. What I'm looking for is a way to trigger the opening of a menu when a long hold or ...

What is the proper method of inserting data into a JSON response?

Looking to enhance my JSON response by adding metadata through a Python request.post. Starting with this structure: {   "key" : "value" } And transforming it into: {   "key" : "value"   "metadata" : { ...

How can I assign the output of a function to a variable within a class in Angular?

Is there a way for the Army class to automatically update its CP property with the sum of CP values from all Detachments in the Detachment class? In the Army class, the CP property should reflect the total CP value from all Detachments and be accessible t ...

Unable to register click event, encountering an error message stating, "co.console.log() is not a function."

I've been attempting to create a button that navigates to another page while passing an object in the parameters. However, I keep encountering an error message: "co. is not a function." It's perplexing because I receive the same error when tr ...

Error Message: Fatal error encountered - TS6046: The value provided for the '--moduleResolution' option is invalid. Valid options include: 'node', 'classic', 'node16', 'nodenext

As I develop a next.js web app with typescript and tailwind CSS, I encountered an issue. When running yarn dev in the terminal, I received this error message: FatalError: error TS6046: Argument for '--moduleResolution' option must be: 'node ...

Issues with $.getjson and trouble with storing JSON data

My current issue involves attempting a getJSON call to a page on my domain that contains a simple JSON array. However, the script in my webpage is not returning anything as expected. <script> $('#genButton').click(function() { ...

Angular - optimizing performance with efficient HTTP response caching tactics

I'm managing numerous services that make requests to a REST service, and I'm looking for the optimal method to cache the data obtained from the server for future use. Can someone advise on the most effective way to store response data? ...

Verify the validity of an image URL

I am attempting to create a function in TypeScript that checks the validity of an image source URL. If the URL is valid, I want to display the image using React Native Image. If the URL is invalid, I would like to replace it with a local placeholder imag ...