IP_PIbd-21_Potapov_Frontend/src/hooks/PostInputFormHook.js

111 lines
3.2 KiB
JavaScript

import { useState } from "react";
import { getBase64FromFile } from "../utils/base64";
import PostsApiService from "../services/PostsApiService";
import toast from "react-hot-toast";
export const usePostInputForm = (user, handlePostsChange) => {
const [postInputFormRefresh, setPostInputFormRefresh] = useState(false);
const refreshForm = () => setPostInputFormRefresh(!postInputFormRefresh);
const [postImage, setPostImage] = useState(null);
const [postText, setPostText] = useState("");
const [imageCheck, setImageCheck] = useState(false);
const [postId, setPostId] = useState(null);
const postInputForm = {
textInput: document.getElementById("post-editor"),
imageInput: document.getElementById("input-title-image"),
selectedImage: document.getElementById("selected-title-image")
? document.getElementById("selected-title-image").src
: null,
imageCheck: document.getElementById("check-title-image"),
postIdInput: document.getElementById("post-input-id"),
};
const handlePostInputFormChange = () =>
setPostInputFormRefresh(!postInputFormRefresh);
const setImage = async (image, isBlob = true) => {
if (image) {
if (!isBlob) {
setPostImage(image);
} else {
setPostImage(await getBase64FromFile(image));
}
} else {
setPostImage(null);
}
setImageCheck(true);
};
const onImageChange = async (event) => {
await setImage(
event.target.files.length != 0 ? event.target.files[0] : null
);
};
const onTextChange = (event) => {
setPostText(event.target.value);
};
const onFormCanceled = () => {
toast.error("Изменения сброшены");
onFormClear();
};
const onFormClear = () => {
setPostText("");
setPostImage(null);
setPostId(null);
handlePostsChange();
refreshForm();
};
const onFormSubmit = async () => {
let post = {
userId: user.id,
html: postText,
};
if (imageCheck) {
post = {
...post,
image: postImage,
};
}
if (postText.trim() == "" && postImage == null) {
toast.error("Заполните пост");
} else {
if (postId) {
const postObj = await PostsApiService.get(postId);
post.pubDate = postObj.pubDate;
await PostsApiService.update(postId, post);
toast.success("Изменения сохранены");
} else {
post.pubDate = new Date();
await PostsApiService.create(post);
toast.success("Пост опубликован");
}
onFormClear();
}
};
return {
postImage,
setPostImage,
onImageChange,
postText,
setPostText,
onTextChange,
postId,
setPostId,
imageCheck,
onFormSubmit,
postInputForm,
handlePostInputFormChange,
setImage,
onFormCanceled,
};
};