Blog Create,Update,View page with api integration and delete api integration Done

This commit is contained in:
Sibunnayak 2024-04-01 16:23:50 +05:30
parent 26ad51abb4
commit f1e0113b06
8 changed files with 830 additions and 501 deletions

View File

@ -48,6 +48,7 @@
"country-state-city": "^3.2.1", "country-state-city": "^3.2.1",
"draft-js": "^0.11.7", "draft-js": "^0.11.7",
"draft-js-export-html": "^1.4.1", "draft-js-export-html": "^1.4.1",
"draft-js-import-html": "^1.4.1",
"md5": "^2.3.0", "md5": "^2.3.0",
"moment": "^2.30.1", "moment": "^2.30.1",
"prop-types": "^15.7.2", "prop-types": "^15.7.2",

View File

@ -253,7 +253,7 @@ const _nav = [
{ {
component: CNavGroup, component: CNavGroup,
name: "Blog", name: "Blog",
icon: <CIcon icon={cilCart} customClassName="nav-icon" />, icon: <CIcon icon={cilNotes} customClassName="nav-icon" />,
items: [ items: [
{ {
component: CNavItem, component: CNavItem,

View File

@ -118,6 +118,8 @@ import EditTestimonial from "./views/Testimonials/EditTestimonial";
//Blogs //Blogs
import Blogs from "./views/Blog/Blogs"; import Blogs from "./views/Blog/Blogs";
import CreateBlog from "./views/Blog/CreateBlog"; import CreateBlog from "./views/Blog/CreateBlog";
import UpdateBlog from "./views/Blog/EditBlog";
import ViewBlog from "./views/Blog/ViewBlog";
const routes = [ const routes = [
{ path: "/", exact: true, name: "Home" }, { path: "/", exact: true, name: "Home" },
{ {
@ -492,6 +494,16 @@ const routes = [
name: "Blogs", name: "Blogs",
element: CreateBlog, element: CreateBlog,
}, },
{
path: "/blog/edit/:id",
name: "Blogs",
element: UpdateBlog,
},
{
path: "/blog/view/:id",
name: "Blogs",
element: ViewBlog,
},
]; ];
export default routes; export default routes;

View File

@ -18,34 +18,33 @@ import SearchIcon from "@mui/icons-material/Search";
import Fuse from "fuse.js"; import Fuse from "fuse.js";
import { Typography } from "@material-ui/core"; import { Typography } from "@material-ui/core";
import { AppBlockingSharp } from "@mui/icons-material"; import { AppBlockingSharp } from "@mui/icons-material";
const Blogs = () => { const Blogs = () => {
const token = isAutheticated(); const token = isAutheticated();
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const navigate = useNavigate(); const navigate = useNavigate();
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [success, setSuccess] = useState(true); const [success, setSuccess] = useState(true);
const [productsData, setProductsData] = useState([]); const [BlogsData, setBlogsData] = useState([]);
const [filterData, setFilterData] = useState([]);
const [queryData, setQueryData] = useState([]);
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [itemPerPage, setItemPerPage] = useState(10); const [itemPerPage, setItemPerPage] = useState(10);
const [showData, setShowData] = useState(productsData); const [showData, setShowData] = useState(BlogsData);
const handleShowEntries = (e) => { const handleShowEntries = (e) => {
setCurrentPage(1); setCurrentPage(1);
setItemPerPage(e.target.value); setItemPerPage(e.target.value);
}; };
const getProductsData = async () => { const getBlogsData = async () => {
axios axios
.get(`/api/product/getAll/`, { .get(`/api/v1/blog/getallblog/`, {
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
}) })
.then((res) => { .then((res) => {
setProductsData(res.data?.product); setBlogsData(res?.data?.BlogData);
setLoading(false); setLoading(false);
}) })
.catch((error) => { .catch((error) => {
@ -61,17 +60,17 @@ const Blogs = () => {
}; };
useEffect(() => { useEffect(() => {
getProductsData(); getBlogsData();
}, [success]); }, [success]);
useEffect(() => { useEffect(() => {
const loadData = () => { const loadData = () => {
const indexOfLastPost = currentPage * itemPerPage; const indexOfLastPost = currentPage * itemPerPage;
const indexOfFirstPost = indexOfLastPost - itemPerPage; const indexOfFirstPost = indexOfLastPost - itemPerPage;
setShowData(productsData.slice(indexOfFirstPost, indexOfLastPost)); setShowData(BlogsData.slice(indexOfFirstPost, indexOfLastPost));
}; };
loadData(); loadData();
}, [currentPage, itemPerPage, productsData]); }, [currentPage, itemPerPage, BlogsData]);
const handleDelete = (id) => { const handleDelete = (id) => {
swal({ swal({
@ -84,7 +83,7 @@ const Blogs = () => {
}).then((value) => { }).then((value) => {
if (value === true) { if (value === true) {
axios axios
.delete(`/api/product/delete/${id}`, { .delete(`/api/v1/blog/deleteblog/${id}`, { // Correct the API endpoint
headers: { headers: {
"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
@ -93,7 +92,7 @@ const Blogs = () => {
.then((res) => { .then((res) => {
swal({ swal({
title: "Deleted", title: "Deleted",
text: "Product Deleted successfully!", text: "Blog Deleted successfully!",
icon: "success", icon: "success",
button: "ok", button: "ok",
}); });
@ -111,54 +110,24 @@ const Blogs = () => {
} }
}); });
}; };
const [filterCategory, setFilterCategory] = useState("");
const handleSearchClick = (query) => {
const option = {
isCaseSensitive: true,
includeScore: false,
shouldSort: true,
includeMatches: false,
findAllMatches: false,
minMatchCharLength: 1,
location: 0,
threshold: 0.6,
distance: 100,
useExtendedSearch: true,
ignoreLocation: false,
ignoreFieldNorm: false,
fieldNormWeight: 1,
keys: ["name"],
};
const fuse = new Fuse(productsData, option);
const result = fuse.search(query);
const searchedResult = result.map((result) => result.item);
console.log(searchedResult);
setQueryData(searchedResult);
};
useEffect(() => {
if (query !== "") {
setFilterCategory("");
}
setTimeout(() => handleSearchClick(query), 100);
}, [query]);
useEffect(() => { useEffect(() => {
setTimeout(() => { setTimeout(() => {
if (filterCategory !== "") { if (query !== "") {
const filteredProducts = productsData.filter( let searchedResult = [];
(product) => product.category?.categoryName === filterCategory searchedResult = BlogsData.filter((item) =>
item.title.toString().includes(query)
); );
setFilterData(filteredProducts); setShowData(searchedResult);
} else { }
// If no category is selected, show all products else{
setShowData(productsData); getBlogsData();
// setFilterData(filteredProducts);
} }
}, 100); }, 100);
}, [filterCategory, productsData]); }, [query]);
return ( return (
<div className="main-content"> <div className="main-content">
<div className="page-content"> <div className="page-content">
@ -167,11 +136,11 @@ const Blogs = () => {
<div className="col-12"> <div className="col-12">
<div <div
className=" className="
page-title-box page-title-box
d-flex d-flex
align-items-center align-items-center
justify-content-between justify-content-between
" "
> >
<div style={{ fontSize: "22px" }} className="fw-bold"> <div style={{ fontSize: "22px" }} className="fw-bold">
Blogs Blogs
@ -201,20 +170,20 @@ const Blogs = () => {
<div className="col-lg-12"> <div className="col-lg-12">
<div className="card"> <div className="card">
<div className="card-body"> <div className="card-body">
<div className="row ml-0 mr-0 mb-10 "> <div className="row ml-0 mr-0 mb-10">
<div className="col-sm-12 col-md-12"> <div className="col-sm-12 col-md-12">
<div className="dataTables_length"> <div className="dataTables_length">
<label className="w-100 d-flex gap-2 align-items-center"> <label className="w-100 d-flex gap-2 align-items-center">
Show : Show :
<select <select
style={{ width: "5%" }} style={{ width: "50px" }}
name="" name=""
onChange={(e) => handleShowEntries(e)} onChange={(e) => handleShowEntries(e)}
className=" className="
select-w select-w
custom-select custom-select-sm custom-select custom-select-sm
form-control form-control-sm form-control form-control-sm
" "
> >
<option value="10">10</option> <option value="10">10</option>
<option value="25">25</option> <option value="25">25</option>
@ -240,7 +209,7 @@ const Blogs = () => {
marginRight: "1rem", marginRight: "1rem",
}} }}
> >
Search by Blog name : Search by Blog Title :
</Typography> </Typography>
<TextField <TextField
style={{ style={{
@ -248,10 +217,11 @@ const Blogs = () => {
padding: "0.5rem", padding: "0.5rem",
borderRadius: "8px", borderRadius: "8px",
flex: "1", flex: "1",
border: " 1px solid grey", border: "1px solid grey",
marginRight: "2rem", marginRight: "2rem",
height: "3rem", height: "3rem",
position: "relative", position: "relative",
width: "300px",
}} }}
placeholder="Search here..." placeholder="Search here..."
variant="standard" variant="standard"
@ -264,7 +234,6 @@ const Blogs = () => {
sx={{ sx={{
background: "white", background: "white",
color: "grey", color: "grey",
// marginTop: "0.1rem",
height: "2.9rem", height: "2.9rem",
width: "3rem", width: "3rem",
position: "absolute", position: "absolute",
@ -272,7 +241,7 @@ const Blogs = () => {
top: "-8px", top: "-8px",
borderRadius: "0px 8px 8px 0px", borderRadius: "0px 8px 8px 0px",
}} }}
onClick={() => handleSearchClick(query)} // onClick={() => handleSearchClick(query)}
> >
<SearchIcon fontSize="small" /> <SearchIcon fontSize="small" />
</IconButton> </IconButton>
@ -312,342 +281,97 @@ const Blogs = () => {
<tbody> <tbody>
{!loading && showData.length === 0 && ( {!loading && showData.length === 0 && (
<tr className="text-center"> <tr className="text-center">
<td colSpan="6"> <td colSpan="4">
<h5>No Data Available</h5> <h5>No Data Available</h5>
</td> </td>
</tr> </tr>
)} )}
{loading ? ( {loading ? (
<tr> <tr>
<td className="text-center" colSpan="6"> <td className="text-center" colSpan="4">
Loading... Loading...
</td> </td>
</tr> </tr>
) : query === "" && filterCategory == "" ? (
showData.map((product, i) => {
return (
<tr key={i}>
<th>
{/* {product.image &&
product.image.map((i, j) => (
<img
key={j}
className="me-2"
src={`${i?.url}`}
width="40"
alt=""
/>
))} */}
{product.image && (
<img
key="test"
className="me-2"
src="https://img.freepik.com/free-photo/pink-headphones-wireless-digital-device_53876-96804.jpg"
width="40"
alt=""
/>
)}
</th>
{/* <td className="text-start">{product.name}</td> */}
<td>
The All new Samsumg s22 Ultra stormed the
market of India
</td>
{/* <td className="text-start">
{product.category?.categoryName !== ""
? product.category?.categoryName
: "Category Not selected "}
</td> */}
<td className="text-start">
{new Date(product.createdAt).toLocaleString(
"en-IN",
{
weekday: "short",
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true,
}
)}
</td>
<td className="text-start">
<Link to={`/product/view/${product._id}`}>
<button
style={{
color: "white",
marginRight: "1rem",
}}
type="button"
className="
btn btn-primary btn-sm
waves-effect waves-light
btn-table
mx-1
mt-1
"
>
View
</button>
</Link>
<Link to={`/product/edit/${product._id}`}>
<button
style={{
color: "black",
backgroundColor: "white",
marginRight: "1rem",
borderColor: "black",
}}
type="button"
className="
btn btn-info btn-sm
waves-effect waves-light
btn-table
mt-1
mx-1
"
>
Edit
</button>
</Link>
<Link
to={"#"}
style={{
marginRight: "1rem",
}}
>
<button
style={{ color: "white" }}
type="button"
className="
btn btn-danger btn-sm
waves-effect waves-light
btn-table
mt-1
mx-1
"
onClick={() => {
handleDelete(product._id);
}}
>
Delete
</button>
</Link>
</td>
</tr>
);
})
) : query !== "" ? (
queryData.map((product, i) => {
return (
<tr key={i}>
<th>
{product.image &&
product.image.map((i, j) => (
<img
key={j}
className="me-2"
src={`${i?.url}`}
width="40"
alt=""
/>
))}
</th>
<td className="text-start">{product.name}</td>
<td className="text-start">
{product.category !== ""
? product.category?.categoryName
: "Category Not selected "}
</td>
<th className="text-start">{product.price}</th>
<td className="text-start">
{new Date(product.createdAt).toLocaleString(
"en-IN",
{
weekday: "short",
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true,
}
)}
</td>
<td className="text-start">
<Link to={`/product/view/${product._id}`}>
<button
style={{
color: "white",
marginRight: "1rem",
}}
type="button"
className="
btn btn-primary btn-sm
waves-effect waves-light
btn-table
mx-1
mt-1
"
>
View
</button>
</Link>
<Link to={`/product/edit/${product._id}`}>
<button
style={{
color: "white",
marginRight: "1rem",
}}
type="button"
className="
btn btn-info btn-sm
waves-effect waves-light
btn-table
mt-1
mx-1
"
>
Edit
</button>
</Link>
<Link
to={"#"}
style={{
marginRight: "1rem",
}}
>
<button
style={{ color: "white" }}
type="button"
className="
btn btn-danger btn-sm
waves-effect waves-light
btn-table
mt-1
mx-1
"
onClick={() => {
handleDelete(product._id);
}}
>
Delete
</button>
</Link>
</td>
</tr>
);
})
) : ( ) : (
query == "" && showData.map((blog, index) => (
filterData.map((product, i) => { <tr key={index}>
return ( <td>
<tr key={i}> {blog.image && (
<th> <img
{product.image && src={blog.image.url}
product.image.map((i, j) => ( alt="Blog Thumbnail"
<img width="40"
key={j} className="me-2"
className="me-2" />
src={`${i?.url}`} )}
width="40" </td>
alt="" <td className="text-start">{blog.title}</td>
/> <td className="text-start">
))} {new Date(blog.createdAt).toLocaleString(
</th> "en-IN",
<td className="text-start">{product.name}</td> {
<td className="text-start"> weekday: "short",
{product.category?.categoryName} month: "short",
</td> day: "numeric",
<th className="text-start">{product.price}</th> year: "numeric",
<td className="text-start"> hour: "numeric",
{new Date(product.createdAt).toLocaleString( minute: "numeric",
"en-IN", hour12: true,
{ }
weekday: "short", )}
month: "short", </td>
day: "numeric", <td className="text-start">
year: "numeric", <Link to={`/blog/view/${blog._id}`}>
hour: "numeric", <button
minute: "numeric", style={{ color: "white", marginRight: "1rem" }}
hour12: true, type="button"
} className="
)}
</td>
<td className="text-start">
<Link to={`/product/view/${product._id}`}>
<button
style={{
color: "white",
marginRight: "1rem",
}}
type="button"
className="
btn btn-primary btn-sm btn btn-primary btn-sm
waves-effect waves-light waves-effect waves-light
btn-table btn-table
mx-1 mx-1
mt-1 mt-1
" "
>
View
</button>
</Link>
<Link to={`/product/edit/${product._id}`}>
<button
style={{
color: "white",
marginRight: "1rem",
}}
type="button"
className="
btn btn-info btn-sm
waves-effect waves-light
btn-table
mt-1
mx-1
"
>
Edit
</button>
</Link>
<Link
to={"#"}
style={{
marginRight: "1rem",
}}
> >
<button View
style={{ color: "white" }} </button>
type="button" </Link>
className=" <Link to={`/blog/edit/${blog._id}`}>
<button
style={{ color: "white", marginRight: "1rem" }}
type="button"
className="
btn btn-info btn-sm
waves-effect waves-light
btn-table
mt-1
mx-1
"
>
Edit
</button>
</Link>
<button
style={{ color: "white" }}
type="button"
className="
btn btn-danger btn-sm btn btn-danger btn-sm
waves-effect waves-light waves-effect waves-light
btn-table btn-table
mt-1 mt-1
mx-1 mx-1
" "
onClick={() => { onClick={() => handleDelete(blog._id)}
handleDelete(product._id); >
}} Delete
> </button>
Delete </td>
</button> </tr>
</Link> ))
</td>
</tr>
);
})
)} )}
</tbody> </tbody>
</table> </table>
</div> </div>
<div className="row mt-20"> <div className="row mt-20">
<div className="col-sm-12 col-md-6 mb-20"> <div className="col-sm-12 col-md-6 mb-20">
<div <div
@ -659,9 +383,9 @@ const Blogs = () => {
Showing {currentPage * itemPerPage - itemPerPage + 1} to{" "} Showing {currentPage * itemPerPage - itemPerPage + 1} to{" "}
{Math.min( {Math.min(
currentPage * itemPerPage, currentPage * itemPerPage,
productsData.length BlogsData.length
)}{" "} )}{" "}
of {productsData.length} entries of {BlogsData.length} entries
</div> </div>
</div> </div>
@ -709,7 +433,7 @@ const Blogs = () => {
{!( {!(
(currentPage + 1) * itemPerPage - itemPerPage > (currentPage + 1) * itemPerPage - itemPerPage >
productsData.length - 1 BlogsData.length - 1
) && ( ) && (
<li className="paginate_button page-item "> <li className="paginate_button page-item ">
<span <span
@ -728,7 +452,7 @@ const Blogs = () => {
className={ className={
!( !(
(currentPage + 1) * itemPerPage - itemPerPage > (currentPage + 1) * itemPerPage - itemPerPage >
productsData.length - 1 BlogsData.length - 1
) )
? "paginate_button page-item next" ? "paginate_button page-item next"
: "paginate_button page-item next disabled" : "paginate_button page-item next disabled"

View File

@ -26,110 +26,149 @@ const CreateBlog = () => {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [imagesPreview, setImagesPreview] = useState([]); const [image, setimage] = useState(null);
// const [allimage, setAllImage] = useState([]);
const [title, setTitle] = useState(""); const [title, setTitle] = useState("");
const [tag, setTag] = useState([]); //tags array const [tag, setTag] = useState(""); //tags array
const [productImages, setProductImages] = useState([]);
const [blogContent, setBlogContent] = useState(EditorState.createEmpty()); const [blogContent, setBlogContent] = useState(EditorState.createEmpty());
// const [htmlData, setHtmlData] = useState();
const [error, setError] = useState(""); const [error, setError] = useState("");
const handleFileChange = (e) => { const handleFileChange = (e) => {
const files = e.target.files; const files = e.target.files;
// Reset error state
setError("");
// Check the total number of selected files // Check if more than one image is selected
if (productImages.length + files.length > 4) { if (files.length > 1) {
setError("You can only upload up to 4 images."); setError("You can only upload one image.");
return; return;
} }
// Check file types and append to selectedFiles // Check file types and append to selectedFiles
const allowedTypes = ["image/jpeg", "image/png", "image/jpg"]; const allowedTypes = ["image/jpeg", "image/png", "image/jpg"];
const selected = []; const file = files[0]; // Only one file is selected, so we get the first one
for (let i = 0; i < files.length; i++) { if (allowedTypes.includes(file.type)) {
if (productImages.length + selected.length >= 4) { setimage(file);
break; // Don't allow more than 4 images
}
if (allowedTypes.includes(files[i].type)) {
selected.push(files[i]);
}
}
if (selected.length === 0) {
setError("Please upload only PNG, JPEG, or JPG files.");
} else { } else {
setError(""); setError("Please upload only PNG, JPEG, or JPG files.");
setProductImages([...productImages, ...selected]);
} }
}; };
const handelDelete = (image) => { const handelDelete = (image) => {
const filtered = productImages.filter((item) => item !== image); setimage(null);
setProductImages(filtered);
}; };
// const handleSubmit = () => {
// setLoading(true);
// const contentState = blogContent.getCurrentContent();
// const htmlData = stateToHTML(contentState);
// // console.log(title, typeof htmlData, image, tag);
// const formData = new FormData();
// formData.append("title", title);
// formData.append("blog_content", htmlData);
// formData.append("image", image);
// formData.append("tags", tag);
// // for (let entry of formData.entries()) {
// // console.log(entry);
// // }
// axios
// .post(`/api/v1/blog/create`, formData, {
// headers: {
// Authorization: `Bearer ${token}`,
// "Content-Type": "multipart/form-data",
// "Access-Control-Allow-Origin": "*",
// },
// })
// .then((res) => {
// swal({
// title: "Added",
// text: "Blog added successfully!",
// icon: "success",
// button: "ok",
// });
// setLoading(false);
// navigate("/blogs");
// })
// .catch((err) => {
// console.log(err);
// setLoading(false);
// const message = err.response?.data?.message
// ? err.response?.data?.message
// : "Something went wrong!";
// swal({
// title: "Warning",
// text: message,
// icon: "error",
// button: "Retry",
// dangerMode: true,
// });
// });
// };
const handleSubmit = () => { const handleSubmit = () => {
// Check if any of the required fields are empty
if (!title || !image || !tag || !blogContent) {
swal({
title: "Warning",
text: "All fields are required!",
icon: "error",
button: "Retry",
dangerMode: true,
});
return; // Exit the function early if any field is empty
}
setLoading(true); setLoading(true);
const contentState = blogContent.getCurrentContent(); const contentState = blogContent.getCurrentContent();
const htmlData = stateToHTML(contentState); const htmlData = stateToHTML(contentState);
console.log(title, typeof htmlData, productImages, tag);
const formData = new FormData(); const formData = new FormData();
formData.append("title", title); formData.append("title", title);
formData.append("blog_content", htmlData); formData.append("blog_content", htmlData);
formData.append("image", image);
formData.append("tags", tag);
// Append each file from productImages array individually axios
productImages.forEach((file, index) => { .post(`/api/v1/blog/create`, formData, {
formData.append(`image${index}`, file); headers: {
}); Authorization: `Bearer ${token}`,
"Content-Type": "multipart/form-data",
// Append each tag from selected array individually "Access-Control-Allow-Origin": "*",
tag.forEach((tag, index) => { },
formData.append(`tag${index}`, tag); })
}); .then((res) => {
for (let entry of formData.entries()) { swal({
console.log(entry); title: "Added",
} text: "Blog added successfully!",
// axios icon: "success",
// .post(`/api/v1/blog/create`, formData, { button: "ok",
// headers: { });
// Authorization: `Bearer ${token}`, setLoading(false);
// "Content-Type": "multipart/form-data", navigate("/blogs");
// "Access-Control-Allow-Origin": "*", })
// }, .catch((err) => {
// }) console.log(err);
// .then((res) => { setLoading(false);
// swal({ const message = err.response?.data?.message
// title: "Added", ? err.response?.data?.message
// text: "Product added successfully!", : "Something went wrong!";
// icon: "success", swal({
// button: "ok", title: "Warning",
// }); text: message,
// setLoading(false); icon: "error",
// // navigate("/products", { replace: true }); button: "Retry",
// }) dangerMode: true,
// .catch((err) => { });
// console.log(err); });
// setLoading(false);
// const message = err.response?.data?.message
// ? err.response?.data?.message
// : "Something went wrong!";
// swal({
// title: "Warning",
// text: message,
// icon: "error",
// button: "Retry",
// dangerMode: true,
// });
// });
}; };
// console.log(data); // console.log(data);
// console.log(productImages); // console.log(productImages);
// To log the content when needed... // To log the content when needed...
// console.log(tag);
return ( return (
<div className="container"> <div className="container">
<div className="row"> <div className="row">
@ -143,7 +182,7 @@ const CreateBlog = () => {
" "
> >
<div style={{ fontSize: "22px" }} className="fw-bold"> <div style={{ fontSize: "22px" }} className="fw-bold">
Add Product Add Blog
</div> </div>
<div style={{ display: "flex", gap: "1rem" }}> <div style={{ display: "flex", gap: "1rem" }}>
<h4 className="mb-0"></h4> <h4 className="mb-0"></h4>
@ -193,13 +232,14 @@ const CreateBlog = () => {
type="text" type="text"
className="form-control" className="form-control"
id="name" id="name"
placeHolder="enter Title"
value={title} value={title}
onChange={(e) => setTitle(e.target.value)} onChange={(e) => setTitle(e.target.value)}
/> />
{name ? ( {title ? (
<> <>
<small className="charLeft mt-4 fst-italic"> <small className="charLeft mt-4 fst-italic">
{25 - name.length} characters left {25 - title.length} characters left
</small> </small>
</> </>
) : ( ) : (
@ -208,15 +248,19 @@ const CreateBlog = () => {
</div> </div>
<div className="mb-3"> <div className="mb-3">
<label>Tags</label> <label htmlFor="tag" className="form-label">
<TagsInput Tags
</label>
<input
type="text"
value={tag} value={tag}
onChange={setTag} onChange={(e) => setTag(e.target.value)}
name="Tags" className="form-control"
id="tag"
placeHolder="enter Tags" placeHolder="enter Tags"
/> />
<em style={{ fontSize: "0.8rem" }}> <em style={{ fontSize: "0.8rem" }}>
press enter or comma to add new tag enter space or comma to add new tag
</em> </em>
</div> </div>
<div> <div>
@ -273,48 +317,42 @@ const CreateBlog = () => {
<p className="pt-1 pl-2 text-secondary"> <p className="pt-1 pl-2 text-secondary">
Upload jpg, jpeg and png only* Upload jpg, jpeg and png only*
</p> </p>
<Box style={{ display: "flex" }}> {image && (
{productImages && <Box marginRight={"2rem"}>
productImages.map((image, i) => ( <img
<Box marginRight={"2rem"}> src={image ? URL.createObjectURL(image) : ""}
<img alt="BlogImage"
src={URL.createObjectURL(image)} style={{
alt="BlogImage" width: 70,
style={{ height: 70,
width: 70,
height: 70,
marginBottom: "1rem", marginBottom: "1rem",
}} }}
/> />
<DeleteSharpIcon {/* <DeleteSharpIcon
onClick={() => handelDelete(image)} onClick={() => handelDelete(image)}
fontSize="small" fontSize="small"
sx={{ sx={{
color: "white", color: "white",
position: "absolute", position: "absolute",
cursor: "pointer", cursor: "pointer",
padding: "0.2rem", padding: "0.2rem",
background: "black", background: "black",
borderRadius: "50%", borderRadius: "50%",
}} }}
/> /> */}
{/* </IconButton> */} {/* </IconButton> */}
</Box> </Box>
))} )}
</Box>
</div> </div>
<div id="createProductFormImage" className="w-25 d-flex"> {/* <div id="createProductFormImage" className="w-25 d-flex">
{imagesPreview.map((image, index) => (
<img <img
className=" w-50 p-1 " className=" w-50 p-1 "
key={index}
src={image} src={image}
alt="Blog Image Preview" alt="Blog Image Preview"
/> />
))} </div> */}
</div>
</div> </div>
</div> </div>
</div> </div>

419
src/views/Blog/EditBlog.jsx Normal file
View File

@ -0,0 +1,419 @@
import React, { useEffect, useState } from "react";
import Button from "@material-ui/core/Button";
import { Link, useNavigate, useParams } from "react-router-dom";
import swal from "sweetalert";
import axios from "axios";
import { isAutheticated } from "src/auth";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import DeleteSharpIcon from "@mui/icons-material/DeleteSharp";
import {
Box,
FormControl,
IconButton,
MenuItem,
Select,
TextField,
} from "@mui/material";
import { Editor } from "react-draft-wysiwyg";
import { EditorState, convertFromHTML, ContentState } from "draft-js";
import { stateToHTML } from "draft-js-export-html"; // This is for converting Draft.js content state to HTML
import { stateFromHTML } from "draft-js-import-html"; // This is for converting HTML to Draft.js content state
const UpdateBlog = () => {
const token = isAutheticated();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [image, setimage] = useState(null);
const [title, setTitle] = useState("");
const [tag, setTag] = useState(""); //tags array
const [blogContent, setBlogContent] = useState(EditorState.createEmpty());
const [error, setError] = useState("");
const [newUpdatedImages, setNewUpdatedImages] = useState(null);
const [Img, setImg] = useState(true);
const id = useParams()?.id;
//get Blogdata
const getBlog = async () => {
try {
const res = await axios.get(`/api/v1/blog/getoneblog/${id}`, {
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
// console.log(res?.data?.blog);
setTitle(res?.data?.blog?.title);
setimage(res?.data?.blog?.image);
// Convert HTML content to Draft.js EditorState
const contentState = stateFromHTML(res?.data?.blog?.blog_content);
const editorState = EditorState.createWithContent(contentState);
setBlogContent(editorState);
setImg(false);
// Joining the tags array into a string separated by commas
const tagsString = res?.data?.blog?.tags.join(",");
setTag(tagsString);
} catch (err) {
swal({
title: "Error",
text: "Unable to fetch the blog",
icon: "error",
button: "Retry",
dangerMode: true,
});
}
};
useEffect(() => {
getBlog();
}, []);
const handleFileChange = (e) => {
const files = e.target.files;
// Reset error state
setError("");
// Check if more than one image is selected
if (files.length > 1 || Img === false || newUpdatedImages !== null) {
setError("You can only upload one image.");
return;
}
// Check file types and append to selectedFiles
const allowedTypes = ["image/jpeg", "image/png", "image/jpg"];
const file = files[0]; // Only one file is selected, so we get the first one
if (allowedTypes.includes(file.type)) {
setNewUpdatedImages(file);
} else {
setError("Please upload only PNG, JPEG, or JPG files.");
}
};
const handelDelete = async (public_id) => {
const ary = public_id.split("/");
const res = await axios.delete(
`/api/v1/blog/deleteImage/jatinMor/Blog/${ary[2]}`,
{
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
}
);
if (res) {
setimage(null);
setImg(true);
}
};
const handellocalDelete = () => {
setNewUpdatedImages(null);
};
const handleSubmit = () => {
if (title === "" || blogContent === "" || tag === "") {
swal({
title: "Warning",
text: "Fill all mandatory fields",
icon: "error",
button: "Close",
dangerMode: true,
});
return;
}
setLoading(true);
const contentState = blogContent.getCurrentContent();
const htmlData = stateToHTML(contentState);
const formData = new FormData();
formData.append("title", title);
formData.append("blog_content", htmlData);
formData.append("tags", tag);
if (newUpdatedImages !== null) {
formData.append("image", newUpdatedImages);
}
axios
.patch(`/api/v1/blog/updateblog/${id}`, formData, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "multipart/form-data",
"Access-Control-Allow-Origin": "*",
},
})
.then((res) => {
swal({
title: "Updated",
text: "Blog Updated successfully!",
icon: "success",
button: "ok",
});
setLoading(false);
navigate("/blogs", { replace: true });
})
.catch((err) => {
setLoading(false);
const message = err.response?.data?.message
? err.response?.data?.message
: "Something went wrong!";
swal({
title: "Warning",
text: message,
icon: "error",
button: "Retry",
dangerMode: true,
});
});
};
return (
<div className="container">
<div className="row">
<div className="col-12">
<div
className="
page-title-box
d-flex
align-items-center
justify-content-between
"
>
<div style={{ fontSize: "22px" }} className="fw-bold">
Update Blog
</div>
<div style={{ display: "flex", gap: "1rem" }}>
<h4 className="mb-0"></h4>
</div>
<div className="page-title-right">
<Button
variant="contained"
color="primary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
textTransform: "capitalize",
marginRight: "5px",
}}
onClick={() => handleSubmit()}
disabled={loading}
>
{loading ? "Loading" : "Save"}
</Button>
<Link to="/blogs">
<Button
variant="contained"
color="secondary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
textTransform: "capitalize",
}}
>
Back
</Button>
</Link>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-lg-6 col-md-6 col-sm-12 my-1">
<div className="card h-100">
<div className="card-body px-5">
<div className="mb-3">
<label htmlFor="title" className="form-label">
Blog Title
</label>
<input
type="text"
className="form-control"
id="name"
placeHolder="enter Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
{title ? (
<>
<small className="charLeft mt-4 fst-italic">
{25 - title.length} characters left
</small>
</>
) : (
<></>
)}{" "}
</div>
<div className="mb-3">
<label htmlFor="tag" className="form-label">
Tags
</label>
<input
type="text"
value={tag}
onChange={(e) => setTag(e.target.value)}
className="form-control"
id="tag"
placeHolder="enter Tags"
/>
<em style={{ fontSize: "0.8rem" }}>
enter space or comma to add new tag
</em>
</div>
<div>
<label htmlFor="image" className="form-label">
Blog Image
</label>
<Box>
<label htmlFor="upload-Image">
<TextField
style={{
display: "none",
width: "350px",
height: "350px",
borderRadius: "10%",
}}
fullWidth
id="upload-Image"
type="file"
accept=".jpg , .png ,.jpeg"
label="file"
multiple
variant="outlined"
onChange={(e) => handleFileChange(e)}
/>
<Box
style={{ borderRadius: "10%" }}
sx={{
margin: "1rem 0rem",
cursor: "pointer",
width: "100px",
height: "100px",
border: "2px solid grey",
// borderRadius: '50%',
"&:hover": {
background: "rgba(112,112,112,0.5)",
},
}}
>
<CloudUploadIcon
style={{
color: "grey",
margin: "auto",
fontSize: "5rem",
marginLeft: "0.5rem",
marginTop: "0.5rem",
}}
fontSize="large"
/>
</Box>
</label>
</Box>
{error && <p style={{ color: "red" }}>{error}</p>}
<div>
<strong className="fs-6 fst-italic">
*You cannot upload more than 1 image
</strong>
</div>
<Box style={{ display: "flex" }}>
{Img === false && image !== null ? (
<Box marginRight={"2rem"}>
<img
src={image.url}
alt="profileImage"
style={{
width: 70,
height: 70,
marginBottom: "1rem",
}}
/>
<DeleteSharpIcon
onClick={() => handelDelete(image.public_id)}
fontSize="small"
sx={{
color: "white",
position: "absolute",
cursor: "pointer",
padding: "0.2rem",
background: "black",
borderRadius: "50%",
}}
/>
</Box>
) : null}
{newUpdatedImages !== null && Img && (
<Box marginRight={"2rem"}>
<img
src={
newUpdatedImages
? URL.createObjectURL(newUpdatedImages)
: ""
}
// src={newUpdatedImages?.url}
alt="profileImage"
style={{
width: 70,
height: 70,
marginBottom: "1rem",
}}
/>
<DeleteSharpIcon
onClick={() => handellocalDelete()}
fontSize="small"
sx={{
color: "white",
position: "absolute",
cursor: "pointer",
padding: "0.2rem",
background: "black",
borderRadius: "50%",
}}
/>
{/* </IconButton> */}
</Box>
)}
</Box>
</div>
{/* <div id="createProductFormImage" className="w-25 d-flex">
<img
className=" w-50 p-1 "
src={image}
alt="Blog Image Preview"
/>
</div> */}
</div>
</div>
</div>
<div className="col-lg-6 col-md-6 col-sm-12 my-1">
<div className="card h-100">
<div className="card-body px-5">
<label>Blog Content</label>
{/* Note : style at _custom.scss */}
<Editor
editorState={blogContent}
toolbarClassName="blog-toolbar"
wrapperClassName="wrapperClassName"
editorClassName="blog-content"
onEditorStateChange={(editorState) => {
setBlogContent(editorState);
}}
/>
{/* <Button onClick={logContent}>Log Content</Button> */}
</div>
</div>
</div>
</div>
</div>
);
};
export default UpdateBlog;

135
src/views/Blog/ViewBlog.jsx Normal file
View File

@ -0,0 +1,135 @@
import React, { useEffect, useState } from "react";
import Button from "@material-ui/core/Button";
import { Link, useParams } from "react-router-dom";
import swal from "sweetalert";
import axios from "axios";
import { Box } from "@mui/material";
const ViewBlog = () => {
const [image, setImage] = useState(null);
const [title, setTitle] = useState("");
const [tag, setTag] = useState([]);
const [blogContent, setBlogContent] = useState(""); // Changed to string
const { id } = useParams();
const getBlog = async () => {
try {
const res = await axios.get(`/api/v1/blog/getoneblog/${id}`);
setTitle(res?.data?.blog?.title);
setImage(res?.data?.blog?.image);
setTag(res?.data?.blog?.tags);
// setBlogContent(res?.data?.blog?.blog_content);
setBlogContent(addStylesToHTML(res?.data?.blog?.blog_content));
} catch (err) {
console.error(err);
swal({
title: "Error",
text: "Unable to fetch the blog",
icon: "error",
button: "Retry",
dangerMode: true,
});
}
};
const addStylesToHTML = (content) => {
// Example: Add styles to <p> and <ul> elements
content = content.replace(
/<p>/g,
'<p style="fontSize:1.5rem; margin-top: 1rem; text-transform: capitalize;">'
);
content = content.replace(/<ul>/g, '<ul style="list-style-type: circle;">');
return content;
};
useEffect(() => {
getBlog();
}, []);
return (
<div className="container">
<div className="row">
<div className="col-12">
<div className="page-title-box d-flex align-items-center justify-content-between">
<div style={{ fontSize: "22px" }} className="fw-bold">
View Blog
</div>
<div style={{ display: "flex", gap: "1rem" }}>
<h4 className="mb-0"></h4>
</div>
<div className="page-title-right">
<Link to="/blogs">
<Button
variant="contained"
color="secondary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
textTransform: "capitalize",
}}
>
Back
</Button>
</Link>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-lg-12 col-md-12 col-sm-12 my-1">
<div className="card h-100">
<div className="card-body px-5">
<div className="mb-3">
{image && (
<img
src={image.url}
alt="blog"
style={{ width: "100%", height: "50vh" }}
/>
)}
</div>
<h4
className="card-title"
style={{
fontWeight: "bold",
fontSize: "3rem",
marginBottom: "1rem",
textTransform: "capitalize",
}}
>
{title}
</h4>
<Box
sx={{
display: "flex",
flexDirection: "row",
flexWrap: "wrap",
gap: "1rem",
}}
>
{tag.map((tag, index) => (
<div
key={index}
className="badge bg-primary font-size-14"
style={{ padding: "0.5rem" }}
>
#{tag}
</div>
))}
</Box>
<div
dangerouslySetInnerHTML={{ __html: blogContent }}
style={{
fontWeight: 600,
}}
/>
</div>
</div>
</div>
</div>
</div>
);
};
export default ViewBlog;