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

Learn how to toggle the menu list visibility by clicking on a component in Vue

I seem to be having an issue with closing a menu item in vue and vuetify2. Here is the code snippet that I have: <v-menu transition="slide-y-transition" bottom left offset-y nudge-bot ...

Error: Unable to retrieve data through Ajax request

$(document).ready(function(){ /* Fetching Data from TTC for Union Station */ $.getJSON("http://myttc.ca/Union_station.json?callback=?", function(data){ if (routes.length > 0) { // Display the stop details with departur ...

Ways to incorporate a scroll feature and display an iframe using JQuery

Is there a way to animate the appearance of hidden iframes one by one as the user scrolls down the website using jQuery? I have come across some solutions, but they all seem to make them appear all at once. I'm looking for a way to make the iframes s ...

How to utilize FileReader for parsing a JSON document?

I'm currently facing an issue while attempting to read and copy a JSON file uploaded by the user into an array. When using .readAsText(), the returned data includes string formatting elements like \" and \n. Is there a way to utilize FileRe ...

Utilizing Online Resources for Texturing in Three.js

Struggling with adding textures in Three.js. I've encountered issues using local images in Chrome due to security concerns, so I'm interested in applying web images instead. Is there a method to attach an image from a URL to a Three.js mesh? ...

Output various strings to the standard output and stream them individually

Is there a way to redirect each string output to standard out to another command? // Example file: example.js #!/usr/bin/env node process.stdout.write('foo') process.stdout.write('bar') After running ./example.js | wc -m, the total ch ...

Leveraging AngularJS directives and $scope autonomously

Let me provide some context first: Previously, my focus was on developing lightweight, single-page Angular applications. However, in the past few days, I began working on a new project that combines Tapestry and Backbone. It has proven to be quite overwhe ...

Having trouble getting Ajax to function properly with CodeIgniter

Here is the AJAX code snippet: $.ajax({ url: '<?php echo base_url(); ?>deleteRowUsingApiKey/index', //This is the current doc type: "POST", //dataType:'json', // add json datatype to get json data: {name ...

Utilize React MaterialUI's ExpansionPanelSummary by incorporating a counter to a specific div id

I am in need of a feature that will automatically increment a counter in the div id every time the render function is invoked. The main goal is to ensure that each div has a unique identifier. Below is the current render function implementation - render ...

Incorporate a "Back" button following the removal of the navigation bar in a Meteor-Ionic

When working on a Meteor-Angular-ionic app, I encountered a situation where I needed to hide the nav-bar in a template to create a full-screen view using the following code: <ion-view hide-nav-bar="true"> However, I then faced the challenge of addi ...

Encountering issue - SCRIPT5022: Error parsing message from server in Sys.WebForms.PageRequestManagerParserErrorException

I'm in need of assistance. I've developed a web application in .Net 3.5 that utilizes asp.net Master page, update panel, and server controls. The asp.net page created with the Master page includes an update panel that contains other server contro ...

Calculate the difference between the current value and the previous value

As I work on developing an app using vue.js, I am currently facing a minor issue. async fetchCovidDataByDay(){ const res = await fetch(`https://api.covid19api.com/live/country/${this.name}/status/confirmed`); const data = await res.json(); this ...

Using HTML5 and an ASP.NET web method to allow for file uploads

My attempt to upload a file to the server using an HTML5 input control with type="file" is not working as expected. Below is the client-side JavaScript code I am using: var fd = new FormData(); fd.append("fileToUpload", document.getElementById(&ap ...

How can I access a Next.js Application from a set Hostname in my Local Environment?

If I have a Next.js Application that is functioning correctly. It can be accessed through either http://localhost:4000 or http://somehostname.local:4000 To achieve this, I have added the line: 127.0.0.1 somehostname.local to my hosts file. However, ...

Creating PopUp Windows with PHP and JavaScript

There is a function created on my page that opens a pop-up window when clicking on a game-mod name: <SCRIPT language="javascript" type="text/javascript"> function popModData( modName ) { var url = "./modList.php?mod=" + modName; ...

Tips on inserting JS code into React component

I seem to be struggling with integrating my JS code into a React component. I attempted it, but unfortunately made a mess of things. Can anyone provide guidance on how to properly accomplish this? mycomponent.js import React from "react"; import Navbar ...

Having trouble authenticating login using JWT token in Apollo client for Next.js when connecting to GraphQL

I am a beginner in this technology, utilizing Django for the backend and Nextjs for the frontend. My aim is to establish a connection to GraphQL in the backend using JWT with Apollo Client 3.3.8. However, whenever I attempt to connect, I encounter a Grap ...

Vue and Vuex retrieve state data from the server in a single request

When loading the History view, data is fetched from the backend server using a Vuex action called in the created() lifecycle hook. This data is then passed to the history table through a computed function named history(), which accesses the history module ...

Could Enzyme testing be implemented with Next.js (SSR)?

Embarking on my inaugural Next.js project with SSR. Encountering issues when attempting to incorporate Enzyme for ReactJS UI testing. It fails to run, displaying the error message: "React' refers to a UMD global, but the current file is a module ...

Encountering the error `ReferenceError: document is not defined` when trying to deploy a Next.js project on Vercel

I recently worked on a Next JS project and deployed it to Vercel. Initially, everything was running smoothly, so I didn't check the website status for a while. I was just developing it locally and pushing updates to GitHub. However, when I finally rev ...