File size: 2,686 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
import React, { useState } from "react";
import Layout from "../core/Layout";
import { isAuthenticated } from "../auth";
import { Link } from "react-router-dom";
import { createCategory } from "./apiAdmin";
const AddCategory = () => {
const [name, setName] = useState("");
const [error, setError] = useState(false);
const [success, setSuccess] = useState(false);
// destructure user and token from localstorage
const { user, token } = isAuthenticated();
const handleChange = e => {
setError("");
setName(e.target.value);
};
const clickSubmit = e => {
e.preventDefault();
setError("");
setSuccess(false);
// make request to api to create category
createCategory(user._id, token, { name }).then(data => {
if (data.error) {
setError(data.error);
} else {
setError("");
setSuccess(true);
}
});
};
const newCategoryFom = () => (
<div className="card p-3 my-4">
<form onSubmit={clickSubmit}>
<div className="form-group">
<label className="text-muted">Name</label>
<input
type="text"
className="form-control"
onChange={handleChange}
value={name}
autoFocus
required
/>
</div>
<button className="btn btn-info">Create Category</button>
</form>
</div>
);
const showSuccess = () => {
if (success) {
return <h3 className="text-success my-2 p-2 border shadow border-success rounded">{name} is created</h3>;
}
};
const showError = () => {
if (error) {
return <h3 className="text-danger my-2 p-2 border shadow border-danger rounded">Category should be unique</h3>;
}
};
const goBack = () => (
<div className="my-5">
<Link to="/admin/dashboard" className="text-warning p-3 my-3 border-warning border">
Back to Dashboard
</Link>
</div>
);
return (
<Layout
title="Add a new category"
description={`G'day ${user.name}, ready to add a new category?`}
>
<div className="row">
<div className="col-md-8 offset-md-2">
{showSuccess()}
{showError()}
{newCategoryFom()}
{goBack()}
</div>
</div>
</Layout>
);
};
export default AddCategory;
|