Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
2.9 kB
1
Indexable
Never
import React, { useEffect, useState } from "react";
import "./NewBoxer.css";
import axios from "axios";
import { useHistory } from "react-router";
import { API_URL } from "../api/auth";

function NewBoxer() {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [height, setHeight] = useState("");
  const [weight, setWeight] = useState("");
  const [reach, setReach] = useState("");
  const [stance, setStance] = useState("");
  const [gym, setGym] = useState("");
  const [gyms, setGyms] = useState([]);
  const [avatar, setAvatar] = useState(null);
  const [loading, setLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [data, setData] = useState(null);
  const [formData, setFormData] = useState("");
  const history = useHistory();

  const handleSubmit = () => {
    setLoading(true);
    setIsError(false);

    const formData = new FormData();
    formData.append('file',avatar);


    const data = {
      first_name: firstName,
      last_name: lastName,
      height: height,
      weight: weight,
      reach: reach,
      stance: stance,
      gym_id: gym,
      avatar: avatar,
    };



    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
  
    
    axios.post(`${API_URL}/boxers`, data, config).then((res) => {
      setData(res.data);
      setFirstName("");
      setLastName("");
      setHeight("");
      setWeight("");
      setReach("");
      setStance("");
      setGym("");
      setAvatar(avatar);
      setLoading(false);
      history.push("/fighters/");
    });
  };

  useEffect(() => {
    axios
      .get(`${API_URL}/gyms`)
      .then((response) => {
        setGyms(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);


  return (
    <div className="container">
      <div style={{ maxWidth: 350 }}>
        <div className="form-group">


        // Other inputs hidden //


 
          <label htmlFor="avatar" className="mt-2">
              Choose An Avatar
          </label>
          <input
              type="file"
              className="form-control"
              id="avatar"
              placeholder="Avatar"
              onChange={(e) => setAvatar(e.target.files[0])
            }
              value={avatar}
              src={avatar}
            />
        </div>



        {isError && (
          <small className="mt-3 d-inline-block text-danger">
            Something went wrong. Please try again later.
          </small>
        )}
        <button
          type="submit"
          className="btn btn-primary mt-3"
          onClick={handleSubmit}
          disabled={loading}
        >
          {loading ? "Loading..." : "Submit"}
        </button>
      </div>
    </div>
  );
}

export default NewBoxer;