Untitled

mail@pastecode.io avatar
unknown
plain_text
4 days ago
5.0 kB
0
Indexable
Never
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Input, Button, Modal, notification, Form, Table } from "antd";
import "../../css/admin.css";

function Blogs() {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isModalVisible1, setIsModalVisible1] = useState(false);
  const [selectedBlog, setSelectedBlog] = useState(null);
  const [blogs, setBlogs] = useState([]);
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [author, setAuthor] = useState("");
  const [imageurls, setImageurls] = useState(Array(4).fill(""));

  const user = JSON.parse(localStorage.getItem("currentUser"));

  const onImageUpload = (index, imageFile) => {
    setImageurls((prevImageurls) => {
      const newImageurls = [...prevImageurls];
      newImageurls[index] = imageFile;
      return newImageurls;
    });
  };

  useEffect(() => {
    fetchBlogs();
  }, []);

  const fetchBlogs = async () => {
    try {
      const response = await axios.get("/api/blog/getallblogs");
      setBlogs(response.data.blogs);
    } catch (error) {
      console.error("Error fetching blogs:", error);
    }
  };

  const deleteBlog = async () => {
    try {
      const response = await axios.patch("/api/blog/deleteblog", {
        _id: selectedBlog._id,
      });
      notification.success({
        message: "Success",
        description: response.data,
      });
      fetchBlogs();
      setIsModalVisible1(false);
    } catch (error) {
      console.error("Error deleting blog:", error);
    }
  };

  const showDeleteConfirm = (blog) => {
    setSelectedBlog(blog);
    setIsModalVisible1(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
    createBlog();
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setTitle("");
    setDescription("");
    setAuthor("");
    setImageurls(Array(4).fill(""));
  };

  const createBlog = async () => {
    const formData = new FormData();
    formData.append("title", title);
    formData.append("description", description);
    formData.append("author", author);

    imageurls.forEach((image, index) => {
      if (image) {
        formData.append("images", image, ${user._id}-${index}.jpg);
      }
    });

    try {
      const response = await axios.post("/api/blog/addblog", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      notification.success({
        message: "Success",
        description: "Blog Created Successfully!",
      });
      fetchBlogs();
      handleCancel();
    } catch (error) {
      console.error("Error creating blog:", error);
      notification.error({
        message: "Error",
        description: "Error creating blog. Please try again.",
      });
    }
  };

  const columns = [
    {
      title: "Title",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "Description",
      dataIndex: "description",
      key: "description",
    },
    {
      title: "Author",
      dataIndex: "author",
      key: "author",
    },
    {
      title: "Actions",
      key: "actions",
      render: (text, record) => (
        <Button type="link" onClick={() => showDeleteConfirm(record)}>
          Delete
        </Button>
      ),
    },
  ];

  return (
    <div className="blogs-comp">
      <div className="ph-header">
        <h3>Blogs</h3>
        <Button onClick={() => setIsModalVisible(true)}>Create Blog</Button>
      </div>
      <div className="bc-table">
        <Table dataSource={blogs} columns={columns} rowKey="_id" />
      </div>
      <Modal
        title="Delete Blog"
        visible={isModalVisible1}
        onOk={deleteBlog}
        onCancel={() => setIsModalVisible1(false)}
      >
        <p>Are you sure you want to delete this blog?</p>
      </Modal>
      <Modal
        title="Create Blog"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={650}
      >
        <Form>
          <Form.Item label="Title" name="title">
            <Input
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
          </Form.Item>
          <Form.Item label="Author" name="author">
            <Input
              value={author}
              onChange={(e) => setAuthor(e.target.value)}
            />
          </Form.Item>
          <Form.Item label="Description" name="description">
            <Input.TextArea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </Form.Item>
          {Array(4).fill(0).map((_, index) => (
            <Form.Item key={index} label={Image ${index + 1}}>
              <Input
                type="file"
                onChange={(e) => onImageUpload(index, e.target.files[0])}
              />
            </Form.Item>
          ))}
        </Form>
      </Modal>
    </div>
  );
}

export default Blogs;
Leave a Comment