Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetching data everytime user is typing

I am trying to fetch data from GitHub API, so basically I want to fetch the actual data when the user click on submit button.
But it fetches the data as the user types.

const [inputText, setInputText] = useState('');
  const [data, setData] = useState({ data: [] });

  useEffect(() => {
    axios
      .get(`https://api.github.com/users/${inputText}/repos`)
      .then((response) => {
        setData(response.data);
      })
      .catch((error) => {
        console.log('error', error);
      });
  }, [inputText]);

  const handleSubmit = (e: React.MouseEvent<HTMLElement>) => {
    e.preventDefault();
    console.log(data);
  };

  const inputHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.preventDefault();
    setInputText(e.target.value);
  };

and here is my JSX:

return (
    <>
      <nav>
        <ul>
          <li>
            <Link to="/history">History</Link>
          </li>
        </ul>
      </nav>
      <h3>GitHub API</h3>
      <TextField
        onChange={inputHandler}
        variant="outlined"
        label="Search for a user"
      />
      <Button variant="contained" onClick={handleSubmit}>
        Submit
      </Button>
    </>
  );

Any help would be appreciated thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your useEffect has a dependency with inputText which means any time that value changes the action wrapped in useEffect is called. From what you provided, you can simply move the functionality from the useEffect into handleSubmit:

  const handleSubmit = (e: React.MouseEvent<HTMLElement>) => {
    axios
      .get(`https://api.github.com/users/${inputText}/repos`)
      .then((response) => {
        setData(response.data);
      })
      .catch((error) => {
        console.log('error', error);
      })
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading