3

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: 'test@gmail.com', 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};
Bill
  • 4,614
  • 13
  • 77
  • 132

3 Answers3

3

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.

Emil
  • 1,186
  • 1
  • 8
  • 17
2

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 };
Amit
  • 3,662
  • 2
  • 26
  • 34
1

Try This:

import React, { useState } from "react";
import ReactDOM from "react-dom";

const ButtonSpinner = () => {
  const [state, setState] = useState({ loading: false });

  const [email, setEmail] = useState("");
  const [pwd, setPwd] = useState("");

  async function submitForm() {
    setState({ ...state, loading: true });
    const response = await fetch(`https://reqres.in/api/login`, {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: { email, password: pwd }
    });
    const content = await response.json();
    setState({ ...state, loading: false });
  }

  return (
    <React.Fragment>
      <div>
        <label>Email</label>
        <input
          value={email}
          onChange={e => setEmail(e.target.value)}
          type="input"
          id="email"
        />
      </div>
      <div>
        <label>Password</label>
        <input
          value={pwd}
          onChange={e => setPwd(e.target.value)}
          type="password"
          id="password"
        />
      </div>
      <div> USE: "email": "eve.holt@reqres.in", "password": "cityslicka"</div>

      <button className="btn-join" onClick={submitForm}>
        {!state.loading ? "Join Now!" : "Loading"}
      </button>
    </React.Fragment>
  );
};

You Will get the response when it will work.

Here is the example: https://codesandbox.io/s/react-hooks-with-submit-h7c3z

Harish Soni
  • 1,796
  • 12
  • 27