I am currently in the process of creating a blog and have been focusing on implementing an edit post feature. However, I have encountered an issue where when I utilize the ref.update()
method, it indicates that the update was successful but I do not see any changes reflected in the database based on the following code snippet.
Code
import AuthCheck from "../../components/AuthCheck";
import { firestore } from "../../lib/firebase";
import { useDocumentData } from "react-firebase-hooks/firestore";
import { useState, useEffect } from "react";
import { useRouter } from "next/router";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";
import ReactMarkdown from "react-markdown";
import Link from "next/link";
export default function Editposts({}) {
return (
<>
<AuthCheck>
<PostManager />
</AuthCheck>
</>
);
}
const PostManager = () => {
const [preview, setPreview] = useState(false);
const router = useRouter();
const { slug } = router.query;
const postRef = firestore.collection("blogs").doc(slug);
const [post] = useDocumentData(postRef);
return (
<>
<div className="container">
{post && (
<>
<section>
<h1>{post.title}</h1>
<h4>{post.slug}</h4>
<Postform
postRef={postRef}
defaultValues={post}
preview={preview}
/>
</section>
<aside>
<h3>Tools</h3>
<button onClick={() => setPreview(!preview)}>
{preview ? "Edit" : "Preview"}
</button>
<Link href={`/${post.slug}`}>
<button className="btn btn-secondary">Live view</button>
</Link>
{/* <DeletePostButton postRef={postRef} /> */}
</aside>
</>
)}
</div>
</>
);
};
const Postform = ({ postRef, defaultValues, preview }) => {
const { register, handleSubmit, reset, watch } = useForm({
defaultValues,
mode: "onChange",
});
const updatePost = async ({ content, published }) => {
await postRef.update({
content,
published,
});
reset({ content, published });
toast.success("Post updated successfully!");
};
return (
<form onSubmit={handleSubmit(updatePost)}>
{preview && (
<div className="card">
<ReactMarkdown>{watch("content")}</ReactMarkdown>
</div>
)}
<div className={preview ? `d-none`:``}>
<textarea
className='form-control'
name="content"
{...register("test", { required: true })}
></textarea>
<fieldset>
<input
className="form-check-input"
name="published"
type="checkbox"
{...register("test", { required: true })}
/>
<label>Published</label>
</fieldset>
<button type="submit" className="btn btn-secondary">
Save Changes
</button>
</div>
</form>
);
};
After submitting the form, a notification appears stating that the update was successful. Yet upon further inspection of the database, no changes were made. Here is an example image for reference: