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

export default function SearchGithub() {
  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>
  );
}

Hey I'm trying to make this github search app. Whenever I click to submit a username and bring back data, the function doesn't fire until the second click. I'm curious as to why.

nme22
  • 3
  • 1
  • 1
    You can't immediately log state after you've set it. You have to use `useEffect` to watch for changes in the state. `useEffect(() => console.log(data), [data]);` – Andy Jan 27 '22 at 22:15
  • Does this answer your question? [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – juliomalves Jan 29 '22 at 15:07

2 Answers2

2

As Andy said, you can't log state after setting it, but you can use the effect hook to do it. Per the 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.

0

Your function

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

is async function i.e means it needs to be waited during its execution so on your button you need to wait for this promise to finish as well here below is how i would've done it

 <Button
    colorScheme="telegram"
    position="fixed"
    ml="3px"
    onClick={async () => { 
                await handleGithubSearch() 
             }}
  >
    Submit
  </Button>
ndotie
  • 1,830
  • 17
  • 18