score:0

const AddContact = () => {
  const classes = useStyles();
  const { contact } = useSelector((state) => state.data);
  const [state, setState] = useState({
    name: contact.name || "",
    mobile: contact.mobile || "",
    email: contact.email || "",
    address: contact.address || "",
  });
  const [editMode, setEditMode] = useState(false);
  const [error, setError] = useState("");

  let history = useHistory();
  let dispatch = useDispatch();
  const { name, email, mobile, address } = state;

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

  const { id } = useParams();

  useEffect(() => {
    setState(contact);
  }, [editMode]);

  useEffect(() => {
    if (id) {
      setEditMode(true);
      dispatch(getContactStart(id));
    }
  }, [id]);

  console.log("id", id);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!name || !address || !email || !mobile) {
      setError("Please input all input Field");
    } else {
      dispatch(addContactStart(state));
      // setTimeout(() => history.push("/"), 1500);
      history.push("/");
      setError("");
    }
  };
  return (
    <div>
      <Button
        style={{ width: "100px", marginTop: "20px" }}
        variant="contained"
        color="secondary"
        onClick={() => history.push("/")}
      >
        Go Back
      </Button>
      <h2>{!editMode ? "Add User" : "Edit User"}</h2>
      {error && <h3 style={{ color: "red" }}>{error}</h3>}
      <form
        className={classes.root}
        noValidate
        autoComplete="off"
        onSubmit={handleSubmit}
      >
        <TextField
          id="standard-basic"
          label="Name"
          defaultValue={editMode ? contact.name : name}
          name="name"
          type="text"
          onChange={handleInputChange}
        />
        <br />
        <TextField
          id="standard-basic"
          label="Email"
          name="email"
          defaultValue={editMode ? contact.name : name}
          type="email"
          onChange={handleInputChange}
        />
        <br />
        <TextField
          id="standard-basic"
          label="Contact"
          defaultalue={editMode ? contact.mobile : mobile}
          name="mobile"
          type="number"
          onChange={handleInputChange}
        />
        <br />
        <TextField
          id="standard-basic"
          label="Address"
          defaultValue={editMode ? contact.address : address}
          name="address"
          type="text"
          onChange={handleInputChange}
        />
        <br />
        <Button
          style={{ width: "100px" }}
          variant="contained"
          color="primary"
          type="submit"
          onChange={handleInputChange}
        >
          Submit
        </Button>
      </form>
    </div>
  );
};

export default AddContact;

Related Query

More Query from same tag