skip to Main Content
import './App.css';
import Axios from 'axios';
import {useState} from 'react';

function App() {

  const [name, setName] = useState('');

  const fetchData = () => {
    Axios.get(`https://api.agify.io/?name=${name}`).then((res)=> {
      console.log(res.data)
    })
  }

  return (
    <div className="App">
      <input placeholder='Ex. John' onChange={(e)=> {setName(e.target.value)}}></input>
      <button onClick={fetchData()}>Predict your age</button>

      <h1> Predicted age: </h1>
    </div>
  );
}

export default App;

I’m currently learning react.js and i dont understand how this works. I expected that if i write an input the state just saves it and when i click on the button it fetches the data what i want (which is like a random json file with and age and a name from an API) but instead my website fetches an empty json (because there’s nothing in the input box) on rendering the App function, and keep fetching on input change.

2

Answers


  1. Your button’s onClick expression is invoking fetchData and setting its return value as the click handler, instead of setting the fetchData function itself as the click handler.

    Every time your App component renders, fetchData gets called, and updating state triggers a re-render.

    So every time you call setName, you trigger a re-render of the component, which invokes fetchData again.

    The fix is to pass the fetchData function itself as the onClick handler, not the result of invoking fetchData. Remove the ():

    <button onClick={fetchData}>Predict your age</button>
    
    Login or Signup to reply.
  2. The button onClick has a mistake.

      <button onClick={fetchData()}>Predict your age</button>
    

    In this line of code , fetchData() will get triggered on every re-render since you passed it as a function and not a function call. You will have to change this code as follows so that the fetchData is called only when you click the button. This will work .

      <button onClick={fetchData}>Predict your age</button>
    

    "fetchData()" inside the onClick will trigger the function on every re-render and will not wait for the click on the button. If you pass it as a function call "fetchData" , it will only run once you click the button.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search