asd

asd
mail@pastecode.io avatar
unknown
abap
3 years ago
2.5 kB
1
Indexable
Never
import React, { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import axios from "axios";
import "./AddEdit.css";
import { toast } from "react-toastify";

const initialState = {
  id: "",
  name: "",
  phone: "",
  ipAddress: "",
};

const AddEdit = () => {
  const [state, setState] = useState(initialState);

  const { id, name, phone, ipAddress } = initialState;

  const navigate = useNavigate();

  const addContact = async (data) => {
    const response = await axios.post("http://localhost:3001/user", data);
    if (response.status === 200) {
      toast.success(response.data);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!name || !id) {
      toast.error(
        "Please provide value into name & id input field they are mandatory"
      );
    } else {
      addContact(state);
      navigate("/");
    }
  };

  const handleInputChange = (e) => {
    let { name, value } = e.target;
    setState({ ...state, [name]: value });
  };

  return (
    <div style={{ marginTop: "100px" }}>
      <form
        style={{
          display: "table",
          margin: "auto",
          padding: "15px",
          maxwidth: "400px",
          alignContent: "center",
        }}
        onSubmit={handleSubmit}
      >
        <label htmlFor="id">Id</label>
        <input
          type="text"
          id="id"
          name="id"
          placeholder="Enter Id..."
          onChange={handleInputChange}
          value={id}
        />
        <label htmlFor="name">Name</label>
        <input
          type="text"
          id="name"
          name="name"
          placeholder="Enter Name..."
          onChange={handleInputChange}
          value={name}
        />
        <label htmlFor="phone">Phone</label>
        <input
          type="number"
          id="phone"
          name="phone"
          placeholder="Enter phone..."
          onChange={handleInputChange}
          value={phone}
        />
        <label htmlFor="ipAddress">ip Address</label>
        <input
          type="number"
          id="ipAddress"
          name="ipAddress"
          placeholder="Enter Ip Address..."
          value={ipAddress}
          onChange={handleInputChange}
        />

        <input type="submit" value="Add" />
      </form>
    </div>
  );
};

export default AddEdit;