I try to learn react component rendering but the problem is that I have a login page with 2 input field and 1 button as:
function LoginPage() {
const [username, changeUsername] = useState('');
const [password, changePassword] = useState('');
const loginRequest = async (username, password) => {
let response = await service.loginRequest(username, password);
console.log(response);
}
return (
<Card hoverable className='transaction-button-card'>
<h1>Enter username and password</h1>
<input type="text"
placeholder="Username"
onChange={e => changeUsername(e.target.value)}
value={username}></input>
<input type="text"
placeholder="Password"
onChange={e => changePassword(e.target.value)}
value={password}></input>
<Button onClick={loginRequest(username, password)}
className='withdraw-deposit-button'>Login/Deposit</Button>
</Card>
);
}
export default LoginPage;
When the page is rendered the function loginRequest(username, password) automatically triggered once and for every input characters to input fields are also triggering the same function and sending request for each input char. How can I solve this problem? (I don't want to send request automatically when the page is opened and send request with only with button). I would appreciate if you define the problem.
CodePudding user response:
` function LoginPage() {
const [username, changeUsername] = useState('');
const [password, changePassword] = useState('');
const loginRequest = async (username, password) => {
let response = await service.loginRequest(username, password);
console.log(response);
}
return (
<Card hoverable className='transaction-button-card'>
<h1>Enter username and password</h1>
<input type="text"
placeholder="Username"
onChange={e => changeUsername(e.target.value)}
value={username}></input>
<input type="text"
placeholder="Password"
onChange={e => changePassword(e.target.value)}
value={password}></input>
<Button onClick={() => loginRequest(username, password)}
className='withdraw-deposit-button'>Login/Deposit</Button>
</Card>
);
}
export default LoginPage; `