Home > Net >  Fetching data everytime user is typing
Fetching data everytime user is typing

Time:09-17

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!

CodePudding user response:

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);
      })
  };
  • Related