the code is to fetch data from an API and feel free to state any possible improvement i made a button to provoke fetch function and input field to read the value from but just for trial purposes i made the value fixed in the code but the onClick function gets invoked on first render without pressing anything ,if someone could elaborate plz.
class App extends React.Component {
fetcher = async(userName)=>{
debugger; // debugger1
const resp = await fetch(ApiBaseUrl userName);
try{
debugger; // debugger 2
const data = await resp.json();
return data;
}
catch(error){
return "error"
}
}
show = (inputValue) =>
{
this.fetcher(inputValue);
// this.setState({infoHolder: {name:'hossam',age:32}});
debugger; // debugger 3
}
render(){
debugger; // debugger 4
return(
<>
<label>Please enter the name of the profile you would like to show information for :</label>
<br></br>
<input type='text' id = 'UIForProfile'></input>
<br></br>
<button onClick={this.show('input')}>Fetch</button>
</>
);
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
and another question :- the sequence of debuggers executions is as follows : debugger 4 -> debugger1 -> debugger 3 -> debugger 2. why did debugger 3 came before debugger 2 'why did the compiler leave the fetcher function and got back to it and why did the function get invoked when i didn't press the button yet.
CodePudding user response:
You're calling the function directly, instead of passing a function to be called when the button is clicked. You can use an arrow function for this like so:
<button onClick={() => this.show('input')}>Fetch</button>
CodePudding user response:
The function show is invoked on the first render because it is being passed as a callback to the onClick prop of the button, rather than being passed a reference to the function. This is because you are calling the function immediately and passing its return value (which is undefined) to the onClick prop. Instead, you should pass a reference to the function like so:
<button onClick={() => this.show('input')}>Fetch</button>
This way, when the button is clicked, the function is invoked with the correct input.