|
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); |
|
|
|
|
|
const { user, token } = isAuthenticated(); |
|
|
|
const handleChange = e => { |
|
setError(""); |
|
setName(e.target.value); |
|
}; |
|
|
|
const clickSubmit = e => { |
|
e.preventDefault(); |
|
setError(""); |
|
setSuccess(false); |
|
|
|
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; |
|
|