I've managed to hard code the email and password into the fetch request but I want to get the values from the form.
Also when i get the response how to I check that the response code is 200 or 400?
import React, { useState } from 'react';
import loading from '../images/loading.svg';
const ButtonSpinner: React.FC = () => {
const [state, setState] = useState({loading: false});
async function submitForm() {
setState({ ...state, loading: true});
const response = await fetch(`http://127.0.0.01/user/register`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email: '[email protected]', password: 'test'})
});
const content = await response.json();
setState({ ...state, loading: false});
}
return (
<span>
<label>Email</label>
<input type="input" id='email'></input>
</span>
<span>
<label>Password</label>
<input type="password" id="password"></input>
</span>
<button className="btn-join" onClick={submitForm}>
{!state.loading ? 'Join Now!' : <img src={loading} alt="loading" />}
</button>
);
}
export {ButtonSpinner};
Use onChange and save user values to the state.
const [formData, setFormData] = useState({email: "", password: ""})
handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormData({...formData, [e.target.name]: e.target.value})
}
Add a name to inputs so e.target.name knows what to change
<input type="input" id='email' name="email" onChange={handleChange}></input>
Then you can reuse the data from formData. If you want to check the response codes, you can just console.log(response) and do if checks for HTTP codes.
You should handle onChange on all input fields and store that in component state. That was state will have all the values entered into form and anytime you submit form you can use values from component state.
const ButtonSpinner: React.FC = () => {
const [state, setState] = useState({ loading: false });
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
async function submitForm() {
setState({ ...state, loading: true });
console.log({ email, password });
const response = await fetch(`http://127.0.0.01/user/register`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ email, password })
});
const content = await response.json();
setState({ ...state, loading: false });
}
return (
<>
<span>
<label>Email</label>
<input
type="input"
id="email"
onChange={evt => setEmail(evt.target.value)}
/>
</span>
<span>
<label>Password</label>
<input
type="password"
id="password"
onChange={evt => setPassword(evt.target.value)}
/>
</span>
<button className="btn-join" onClick={submitForm}>
{!state.loading ? "Join Now!" : <div>loading</div>}
</button>
</>
);
};
export { ButtonSpinner };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With