Skip to content

Commit

Permalink
feat: use session state to store use markdown
Browse files Browse the repository at this point in the history
  • Loading branch information
MR-Addict committed Oct 31, 2024
1 parent 0a36bcf commit 7b8c452
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/app/form/components/Form/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,19 @@ import { FaRegUser, FaRegEdit } from "react-icons/fa";
import style from "../style.module.css";
import formatDate from "@/lib/utils/formatDate";
import addNoteApi from "@/lib/api/notes/addNoteApi";
import useSessionState from "@/hooks/useSessionState";
import usePersistantState from "@/hooks/usePersistantState";

import Message from "@/components/Message/Message";
import SubmitButton from "../SubmitButton/SubmitButton";
import MarkdownEditor from "@/components/MarkdownEditor/MarkdownEditor";

const cookieName = "punch-last-submit-date";
const cookieName = "last-submit";

export default function Form() {
const [useMarkdown, setUseMarkdown] = useState(false);
const [name, setName] = usePersistantState("form-name", "");
const [content, setContent] = usePersistantState("form-content", "");
const [useMarkdown, setUseMarkdown] = useSessionState("form-usemarkdown", false);

const [pending, setPending] = useState(false);
const [openEditor, setOpenEditor] = useState(false);
Expand All @@ -39,6 +40,7 @@ export default function Form() {
if (res.success) {
setContent("");
setStatus("done");
setUseMarkdown(false);
document.cookie = `${cookieName}=${new Date().toISOString()};max-age=${60 * 60 * 24};path=/;`;
} else toast.error(res.message);

Expand Down
23 changes: 23 additions & 0 deletions src/hooks/useSessionState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Dispatch, SetStateAction, useEffect, useState } from "react";

export default function useSessionState<T>(
key: string,
defaultValue: T,
prefix = "session-state"
): [T, Dispatch<SetStateAction<T>>] {
const [state, setState] = useState<T>(() => {
if (typeof window === "undefined") return defaultValue;

const value = sessionStorage.getItem(`${prefix}-${key}`);
if (typeof value === "string") return JSON.parse(value);
return defaultValue;
});

useEffect(() => {
const callback = () => sessionStorage.setItem(`${prefix}-${key}`, JSON.stringify(state));
const timer = setTimeout(callback, 500);
return () => clearTimeout(timer);
}, [state, key]);

return [state, setState];
}

0 comments on commit 7b8c452

Please sign in to comment.