Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React TypeScript: How to get form values, and response codes using fetch

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};
like image 620
Bill Avatar asked Jun 19 '26 15:06

Bill


2 Answers

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.

like image 100
Emil Avatar answered Jun 21 '26 05:06

Emil


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 };
like image 41
Amit Avatar answered Jun 21 '26 03:06

Amit