Button functions properly after the second click

import { Input, Box, Text, Divider, Button } from '@chakra-ui/react';
import { useState } from 'react';

export default function GithubSearchApp() {
  const [username, setUsername] = useState('');
  const [data, setData] = useState({});

  async function handleGithubSearch() {
    await fetch('/api/github', {
      method: 'POST',
      body: JSON.stringify(username),
    })
      .then((response) => response.json())
      .then((data) => setData(data));
    console.log(data);
  }

  function handleUsername(e) {
    setUsername(e.target.value);
  }

  return (
    <Box>
      <Text fontSize="lg"> Search for GitHub Repositories!</Text>
      <Divider />
      <Input
        placeholder="Enter a GitHub username"
        onChange={handleUsername}
        value={username}
      />
      <Button
        colorScheme="telegram"
        position="fixed"
        ml="3px"
        onClick={handleGithubSearch}
      >
        Submit
      </Button>

      {data ? <h1> {data.login}</h1> : null}
    </Box>
  );
}

Hello, I'm encountering an issue with my GitHub search app. The data is only fetched after the second click when submitting a username. I'm puzzled as to why this delay occurs.

Answer №1

Andy made a good point that you can't log the state after setting it, but there is a workaround using the effect hook. According to the React documentation:

Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component. Instead, use useEffect. The function passed to useEffect will run after the render is committed to the screen. By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.

Answer №2

Here is a sample function for handling GitHub search requests:

 async function handleGithubSearch() {
    await fetch('/api/github', {
      method: 'POST',
      body: JSON.stringify(username),
    })
      .then((response) => response.json())
      .then((data) => setData(data));
    console.log(data);
  }

This function is asynchronous, meaning it needs to be awaited during its execution. To properly utilize this function on a button click event, you should wait for the promise to finish before proceeding. Here's an example of how it can be done:

 <Button
    colorScheme="telegram"
    position="fixed"
    ml="3px"
    onClick={async () => { 
                await handleGithubSearch() 
             }}
  >
    Submit
  </Button>

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

How to grab JSON data within a CakePHP 2.2 controller

Trying to transmit JSON data from a web page using JQuery, as shown below: $.ajax({ type: "post", url: "http://localhost/ajax/login", data: '{username: "wiiNinja", password: "isAnub"}', dataType: "json", contentType: "applica ...

When adding an object to an array in AngularJS, it seems to trigger updates for

Currently, I am fetching data from a WebAPI and then storing it in an array called products, which is scoped. $scope.products In addition to the products array, I also have another scoped array named selectedFish. $scope.selectedFish = []; My objective ...

After a two-second period of inactivity, the buttons on the item should trigger an action

I have a scenario in mind that I want to implement: When the user clicks on either the "Plus" or "Minus" button. If the user doesn't click on any of those buttons within 2 seconds, then we assume that the current quantity should be sent to the server ...

Webpack loaders or plugins: understanding the distinction

Can you explain the distinction between loaders and plugins in webpack? I found on the documentation for plugins that it states: Plugins are used to incorporate extra functionalities usually related to bundles within webpack. While I understand that b ...

jQuery script unable to alter img src in Firefox and IE browsers

I am working with an image and a jQuery script to change the captcha image. <img src="captcha.jpg" id="my-image"/> The jQuery script is as follows: <script> $(document).ready($("#my-image").click(function(){ $('#my-image&ap ...

What is the best way to utilize the history prop in conjunction with other props?

I am currently using react-router-dom along with react. My goal is to include additional props along with the history prop import React from 'react'; function MyComponent({ history }) { function redirect() { history.push('/path&ap ...

Utilizing dynamic jQuery events with variable integration

I'm having some trouble incorporating a variable into a dynamically added jQuery event. Every time I click, the message displayed is "The number is 3" for all div elements. $( document ).ready(function() { for (var i = 0; i < 3; i++) { ...

The $.each function seems to be stuck and not cycling through the

Dealing with a rather intricate JSON structure, I'm encountering difficulty iterating through it using the $.each() function. It seems to be related to the unusual 2-dimensional array passed in the value section of the standard array (hopefully that m ...

Turn off the scrollbar without losing the ability to scroll

Struggling with disabling the HTML scrollbar while keeping the scrolling ability and preserving the scrollbar of a text area. Check out my code here I attempted to use this CSS: html {overflow:hidden;} Although it partially worked, I'm not complete ...

I'm curious if the response order will mirror the URL order in my situation

QUERY: Upon reviewing the following link: Promise.all: Order of resolved values I am doubtful about its relevance to my specific scenario. Can I always expect responses to be in the same order as urls? EXAMPLE: var urls = []; for (var i = 0; i < d ...

Store the link in a variable and retrieve its content into another variable

Is there a way to extract the content of a link stored in a variable and store it in another variable using jQuery or javascript while working on an XML page? I know this is possible with php, but since I am developing a Chrome extension, I am wondering ...

Vue Dynamic Table Title

Is it possible to add labels to a pivot-table in Vue without affecting array indexes and drag-and-drop functionality as shown in the screenshot below? https://i.stack.imgur.com/5JTSM.png Are there alternative methods for implementing this feature? You c ...

Can someone explain the distinction between 'return item' and 'return true' when it comes to JavaScript array methods?

Forgive me for any errors in my query, as I am not very experienced in asking questions. I have encountered the following two scenarios :- const comment = comments.find(function (comment) { if (comment.id === 823423) { return t ...

Creating a Breeze js entity using a JSON string and importing it into the breeze cache: A step-by-step guide

Currently, I am developing a mobile single page website that utilizes technologies like breeze js, angular js, web API, and entity framework. To enhance the performance of the site, I have decided to include the breeze metadata in a bundled JavaScript fil ...

Reducing file size through compression (gzip) on express js version 4.4.1

My express js app is functioning as a web server, but I am having trouble with serving unzipped static content (js and css files). I have tried using compression from https://github.com/expressjs/compression, but it doesn't seem to be working for me. ...

Looking to retrieve the text content of an element using jQuery?

My goal is to use jQuery mobile to transfer a user to a linked page when they click on an <li> element, and then display an alert with the text of the list element they clicked. However, my current implementation only shows an empty alert box. < ...

Creating a multi-tiered cascading menu in a web form: Harnessing the power of

In my form, there is a field called 'Protein Change' that includes a multi-level dropdown. Currently, when a user selects an option from the dropdown (for example, CNV->Deletion), the selection should be shown in the field. However, this function ...

Facing Hurdles in Starting my Debut Titanium Mobile Project

I recently started using Titanium Studio (version 2.1.0GA on WindowsXP) and I have added the Android SDK to it. However, I am encountering an error when trying to run my first mobile project. The console is displaying the following message: Can anyone off ...

Exploring the possibilities of utilizing classes in testing scenarios with Vue, Cypress, and Cucumber

I am currently working on setting up e2e tests using Cypress and Cucumber for my project. The application is built with Vue CLI 4.1.1, and I have added the package cypress-cucumber-preprocessor (V1.19.0) via NPM. Update: After extensive research and tes ...

How to selectively load specific scripts in index.html with the use of angular.js

Let me address a problem I'm facing with a large development project. It seems that the current setup does not function properly on Internet Explorer. My idea is to only load files that are compatible and do not generate errors when accessed through I ...