markdown editor
This commit is contained in:
97
src/components/Markdowns/MarkdownEditor.js
Normal file
97
src/components/Markdowns/MarkdownEditor.js
Normal file
@@ -0,0 +1,97 @@
|
||||
import React, {useContext, useEffect, useState} from "react";
|
||||
import {AuthContext} from "../../AuthProvider";
|
||||
import {useNavigate, useParams} from "react-router-dom";
|
||||
import {fetchWithCache} from "../../utils/fetchWithCache";
|
||||
|
||||
const MarkdownEditor = () => {
|
||||
const {roles} = useContext(AuthContext);
|
||||
const navigate = useNavigate();
|
||||
const {id} = useParams()
|
||||
const [title, setTitle] = useState("");
|
||||
const [content, setContent] = useState("");
|
||||
const [path, setPath] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if(id){
|
||||
fetchWithCache(`/api/markdown/${id}`)
|
||||
.then((data) => {
|
||||
setTitle(data.title);
|
||||
setContent(data.content);
|
||||
setPath(data.path);
|
||||
})
|
||||
.catch((err) => {console.error("failed to load markdown", err)});
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
const handleSave = () => {
|
||||
const url = id ? `/api/markdown/${id}` : "/api/markdown";
|
||||
const method = id ? "PUT" : "POST";
|
||||
fetch (url, {
|
||||
method,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${localStorage.getItem("accessToken")}`,
|
||||
},
|
||||
body: JSON.stringify({title, content, path}),
|
||||
})
|
||||
.then((res) => {
|
||||
if (res.ok) {
|
||||
navigate("/");
|
||||
}else {
|
||||
return res.json().then((data) => {
|
||||
throw new Error(data.error || "Failed to save markdown");
|
||||
})
|
||||
}
|
||||
})
|
||||
.catch((err) => {console.error("failed to load markdown", err)});
|
||||
};
|
||||
|
||||
const hasPermission = roles.includes("admin") || roles.includes("creator");
|
||||
if(! hasPermission)
|
||||
return (
|
||||
<div> Can not crete(Permission Denied)</div>
|
||||
);
|
||||
return (
|
||||
<div>
|
||||
<h2>{id ? "Edit Markdown" : "Create Markdown"}</h2>
|
||||
<form>
|
||||
<div>
|
||||
<label>
|
||||
Title:
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label>
|
||||
Path:
|
||||
<input
|
||||
type="text"
|
||||
value={path}
|
||||
onChange={(e) => setPath(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label>
|
||||
Content:
|
||||
<textarea
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<button type="button" onClick={handleSave}>
|
||||
Save
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
|
||||
|
||||
}
|
||||
|
||||
export default MarkdownEditor;
|
||||
Reference in New Issue
Block a user