Leveraging promises to handle button clicks in stenciljs

I am in the process of developing a stenciljs application and I am trying to fetch data from a REST service. The REST call is set up as a function that returns a Promise. When I use this rest call in the componentWillLoad Lifecycle Method, it functions as expected:

async componentWillLoad() {

return getUserData().then( userData => {
  console.log("got userdata", userData);
});

}

Now, I want to retrieve this information when the user clicks a button. To achieve this, I invoke this method in the click handler for the button:

<button id="mybutton" onClick={()=>this._handleButtonClick()></button>

_handleButtonClick() {
  return getUserData().then( userData => {
  console.log("got userdata", userData);
 });
}

However, this approach does not seem to work. Upon inspecting the Network Tab in the Browser console, I can see that a network request is being made but it does not return any data. How can I resolve this issue?

Answer №1

Seems like there might be a missing closing brace (}) in your code?

onClick={()=>this._handleButtonClick()
<- check here

If it's just a typo, you could try storing the result of getUserData in the state object to trigger the render() function when your data changes.

This is an example of how I perform the fetch:

fetch(`REST endpoint`, {
  method: 'GET',
  headers: { // Content-Type and security token }
}).then((response: Response) => response.json())
  .then(data => {
    this.dataList = data;
  });

In this case, I'm storing the result as "dataList", which is defined with @State() dataList.

Answer №2

It seems like the button you have doesn't include the type="button" attribute.

In some cases, when a button is not explicitly defined as type="button" and it happens to be the first button within a form, the browser may treat it as a

<button type="submit">
. This could lead to unexpected behavior where clicking on the button triggers both the API call due to the listener attached to it and a form submission.

Considering that API calls require time to execute, there's a possibility that by the time the response is received, your page has already reloaded because of the form submit event.

While this situation is somewhat rare, it seems to align with what you've described happening.

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

What is the best method for detecting browser capabilities in an Angular application: service, directive, or controller?

If this question seems too broad or opinion-based, please let me know and I'll work on refining it. I am currently exploring the integration of browser compatibility checks and notifications in an Angular application. Utilizing Modernizr has been rea ...

Customizing Body Color in CKEditor for Dynamic Designs

I am facing an issue with CKEditor that I am hoping to find a solution for. My scenario involves using a jQuery color picker to set the background color of a DIV element, which is then edited by the user in CKEditor. However, I have observed that it is not ...

Error in initializing UI-router wrapper due to circular dependency in Angular.js

I've been following the angular style guide of John Papa (https://github.com/johnpapa/angular-styleguide#routing) and implementing a custom wrapper for angular ui-router as suggested. However, I'm encountering an issue with the wrapper causing a ...

Display or conceal form elements depending on the JSON response

Upon making an api call, a json Response is received with the following structure: {"Field":"Amount","FieldName":"Amount","FieldType":"Numeric","MaximumLength":128,"MinimumLength":0,"Options":"Mandatory"} This api call yields between 5-10 of these object ...

Sending a file using Angular's $http service

I am facing an issue while trying to upload a form with an image file using the angular $http function and multer in the background for receiving. I have successfully uploaded the image via a direct form submission (without angular) as shown below: <fo ...

The proper way to access a JavaScript object with correct syntax

Looking to extract specific values from a JavaScript object? Read on. <script> var market = "arizona"; var marketNumbers = { "arizona" : "800 555-1234|866 452-8569", "florida" : "800 555-4567|866 452-9999" }; for (market in marketNumbers) { var ...

Establish a connection with an existing web driver using Selenium in JavaScript

While I don't claim to be a Selenium expert, there may be something important that I'm overlooking in this situation. One of the software within the company initiates Google Chrome using ChromeDriver. I aim to link up with this browser through ...

Responsive design issues with Bootstrap 3 box layout

I am currently working on creating a bootstrap4 layout that includes three boxes arranged side by side on a wide screen. However, my goal is to ensure that if the screen size decreases, the red and green boxes always stay adjacent to each other while the b ...

How can I retrieve the PHP response once a successful upload has occurred using DropzoneJS?

I am currently in the process of integrating Dropzone into my website. My goal is to capture the "success" event and extract specific information from the server response to add to a form on the same page as the DropZone once the upload is finished. The k ...

Load the ajax content only if the specific class matches the given class name "x

I've created the code below with the expectation that it will only load AJAX if the content hasn't already been loaded into the div. Essentially, when I use AJAX to load the content and assign a class name based on which content is currently disp ...

Receiving a Javascript Callback from Paypal

Is it possible to receive a JavaScript callback after a successful PayPal purchase made using a button? I am aware of IPN, but it requires a return URL. My main goal is to simply determine if a user has completed a purchase with the button. ...

Guide to forming an array by extracting specific properties from a nested JSON array using javascript

Currently, I have this list: list = { id: 1, arr: [ {index : 1 , description: "lol" , author: "Arthur"}, {index : 2 , description: "sdadsa" , author: "Bob"}, {index : 3 , desc ...

Start by retrieving information and then sending properties to a different component

I have been struggling with this issue for more than a week now. Despite thorough reading of the Next.js documentation and extensive online research, I still can't figure out what's wrong. It seems like I must be overlooking something important, ...

What can I do to control the behavior of this shake effect?

Looking for a solution to the following coding issue: jQuery.fn.shake = function(intShakes, intDistance, intDuration) { this.each(function() { $(this).css("position","relative"); for (var x=1; x<=intShakes; x++) { $(this).a ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

Display debugging information in the console using bunyan

child.log.info('info'); child.log.debug('debug'); When running the command: node app.js | bunyan -o short -l debug I am encountering an issue where only INFO messages are displayed and DEBUG messages are not showing up. I want to be ...

I find it strange that this warning message continues to pop up even though there is already a key prop assigned. It keeps saying: "Each child in a list should have a unique 'key'

As a newcomer to React, I find myself puzzled by the recurring appearance of this warning message: Warning: Each child in a list should have a unique "key" prop Even though there is already a key prop present on the element, why does this warn ...

Refreshing Form in Angular 5 post submission

<form class="form-horizontal" name="form" (ngSubmit)="!f.form.invalid && staffDetails(model)" #f="ngForm" novalidate> <div class="form-group"><button [disabled]="f.invalid" *ngIf ="buttonSave" class="btn btn-info">Save</butt ...

Dealing with audio bleed from a previous recording using fluent-ffmpeg

const Discord = require('discord.js'); const client = new Discord.Client(); const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg'); const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegInstaller.path); co ...

How can Vue add a class to an element without using v-model:class?

I am faced with the challenge of connecting two elements that are located in different areas of the DOM. The goal is to create a hover effect on one element when the other is interacted with. The first element is within a component and is rendered using t ...