File size: 3,997 Bytes
f5071ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import { nanoid } from "@reduxjs/toolkit";
import { useEffect, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../context/auth";
import {
  getItemFromLocalStorage,
  removeFromLocalStorage,
  saveToLocalStorage,
} from "../helper/localStorage";
import { createPost, deletePost, draftPost, editPost } from "../lib/api";
import { setTitleToStore } from "../store/post/postData";

const useCreatePost = (currentPostDataToEdit) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const user = useAuth();

  //value from redux store
  const postDataFromStore = useSelector((state) => state.postData);

  const initialState = useMemo(
    () => ({
      cvImg: "",
      title: "",
      tags: [],
      MDEValue: "",
      userId: user?.userId,
    }),
    [user?.userId]
  );

  //states
  const [postData, setPostData] = useState(
    currentPostDataToEdit ||
      getItemFromLocalStorage("postDataToPublish") ||
      initialState
  );
  const [title, setTitle] = useState(postData?.title || "");
  const [uploadingImg, setUploadingImg] = useState(false);
  const [publishing, setPublishing] = useState(false);
  const [savingDraft, setSavingDraft] = useState(false);

  //set title to store
  useEffect(() => {
    dispatch(setTitleToStore(title));
  }, [title, dispatch]);

  //set postData state everytime postData from store change
  useEffect(() => {
    const newData = {
      cvImg: postDataFromStore.cvImg,
      title: postDataFromStore.title,
      tags: postDataFromStore.tags,
      MDEValue: postDataFromStore.MDEValue,
      userId: user?.userId,
    };

    setPostData((prevData) => ({ ...prevData, ...newData }));
  }, [postDataFromStore, user?.userId]);

  //save to localStorage
  useEffect(() => {
    saveToLocalStorage(
      currentPostDataToEdit ? "postDataToManage" : "postDataToPublish",
      JSON.stringify(postData)
    );
  }, [postData, currentPostDataToEdit]);

  const publishPostHandler = () => {
    setPublishing(true);

    if (postData.draft) {
      deletePost(postData.id);
    }

    //if post is a draft , It will have an id but It will be replced with firebase auto generated id when fetch data in [useGetData.js] file

    createPost({ ...postData, draft: false })
      .then((_) => {
        setPublishing(false);
        navigate("/dashboard");
        removeFromLocalStorage("postDataToPublish");
        removeFromLocalStorage("postDataToManage");
        // console.log('created post successfully');
      })
      .catch((err) => {
        setPublishing(false);
        console.log(err);
      });
  };

  const draftPostHandler = () => {
    setSavingDraft(true);

    const route = postData.draft ? -1 : "/dashboard/drafts";

    draftPost({
      ...postData,
      draft: true,
      id: postData.id || nanoid().replaceAll("_", "-"), // underscore must not include in postId because i split post url with underscore to get specific postId
    })
      .then((_) => {
        setSavingDraft(false);
        navigate(route);
        removeFromLocalStorage("postDataToPublish");
        removeFromLocalStorage("postDataToManage");
        // console.log('drafted post successfully');
      })
      .catch((err) => {
        setSavingDraft(false);
        console.log(err);
      });
  };

  const eidtPostHandler = () => {
    setPublishing(true);

    editPost({ ...postData, updated: true })
      .then((_) => {
        setPublishing(false);
        navigate(-1);
        removeFromLocalStorage("postDataToManage");
        // console.log('edited post successfully');
      })
      .catch((err) => {
        setPublishing(false);
        console.log(err);
      });
  };

  return {
    postData,
    title,
    setTitle,
    publishing,
    savingDraft,
    uploadingImg,
    setUploadingImg,
    publishPostHandler,
    draftPostHandler,
    eidtPostHandler,
  };
};

export default useCreatePost;