I attempted to make changes to a Firebase document using the update() function, however, the document did not reflect

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:

https://i.sstatic.net/eBHJ4.jpg

Answer №1

After some investigation, I finally discovered the root of the issue. I realized that the tutorial I was following utilized an outdated version 6.X.X. Upon scouring the internet for a solution, I came across a line of code that I hastily copied and pasted:

{...register("test", { required: true })}
. In my haste, I mistakenly named the field value 'test' instead of 'content'. This oversight caused the problem as there was no corresponding 'test' field to be updated. Hopefully, this insight proves useful to others encountering similar challenges.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transitioning JS/CSS effects when the window is inactive

My latest project involved creating a small slider using JavaScript to set classes every X seconds, with animation done through CSS Transition. However, I noticed that when the window is inactive (such as if you switch to another tab) and then return, the ...

Issue "RangeError: minimumFractionDigits value is invalid" when using ChartJS in a Next.js application

I'm currently working on developing an application utilizing react-chartjs-2.js. The functionality is smooth in my local environment, but when moved to production, I encounter the following error: Application error: a client-side exception has occurre ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...

The operation in Mongo DB carried out a $pull to eliminate the ObjectId("... id") from the nested sub-array

I've scoured every nook and cranny of the internet in an attempt to resolve this issue, but so far I've come up empty-handed. My goal is to use the mongodb $pull function to remove an Object from an array nested inside a Schema. I've success ...

Integrate JavaScript date into the gulp-rev workflow

I have been encountering an issue while using the gulp-rev plugin to add a revision of my app/html page generated by the Yeomann webapp generator. My workflow involves zipping the app and then adding a revision, but I am having trouble replacing the hash t ...

Search field in DataTables appears to be misaligned

I'm in the process of developing a small website using JSP and DataTables (currently only for the first table). Here's what I have so far: As you can observe, there seems to be an alignment issue with the search field position. I'm n ...

Exploring and verifying data within an array in ReactJS

In ReactJS, there is a variable that contains the result of validation as an array: console.log(this.state.check); // [account: false, name: true, email: true] Here's what needs to be done: If all values in the array are true, return true. If one or ...

Best practices for storing non-reactive and static data in a Vue application

Welcome to the community! I'm excited to ask my first question here on StackOverflow. I am currently working with vue.js-v2 and webpack. My goal is to ensure that data remains immutable for child components, which are loaded through the vue-router. T ...

Is there a way in Rollup.js to substitute a dependency package's imported module with a local file?

I am currently working on a JavaScript project that needs to be bundled using Rollup.js. The project depends on package A, which in turn relies on package B: "mypackage" ---import--> "A" ----import----> "B" My package ...

Storing data into Firebase database using a cloud function API

Below is a Firebase cloud function I have created that can be accessed through a REST API. My aim is to save the user-submitted values from the front end via the 'Web service URL': 1.) The data should be stored in the Firebase-realtime database ...

Leveraging the power of JavaScript functions together with the asp:Timer component

<p><b> Progress: <asp:Label ID="progressPercentageLabel" runat="server"></asp:Label>%</b></p> <script> function updateBar() { var bar = document.getElementById("CompletionBar"); ...

JavaScript file encountering a problem with its global variables

What is causing the alert("2") to pop up first instead of it being second? Why am I encountering difficulty creating global variables c and ctx? Is there a way for me to successfully create these two global variables in order to utilize ...

exploring numerous boxes in an engaging and educational tutorial

Explaining this in the title was a bit tricky, but what I want to create is an interactive tutorial. In this tutorial, the user will click on an area or product they want to clean or use for cleaning. After clicking, another box with relevant information w ...

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

Sending parameters dynamically in AJAX chosen

I am completely new to the world of Jquery and need some help. Here are the codes I currently have: $target.ajaxChosen({ type: 'GET', url: '<s:url action="getFilterValueJSON" namespace="/cMIS/timetable"></s:url> ...

Verify the password by checking each character as you type

Currently, I am trying to implement a real-time password matching feature. Is there anyone who can provide me with the code that verifies whether the entered passwords match character by character as they are being typed, and also checks the length upon ...

A step-by-step guide on utilizing the v-for index loop to showcase a nested JSON array

My JSON Array has the following structure: items: [ { ID: 11, UserID: "test.com", UserRole: "user", timeStamp: "2021-03-23T15:54:02.125578", dialogs: [ { "Bot" ...

Triggering Firebase Cloud Functions upon a database event to perform a redirect

Typically, one would use an https trigger in Firebase Cloud Functions for redirection, as shown below. exports.redirect = functions.https.onRequest((request, response) => { response.redirect("laserguidedmissiles.com") }); But how ...

"Utilizing AJAX for real-time search to target the final

Recently, I've been playing around with the AJAX Live Search feature that can be found on this site: http://www.w3schools.com/php/php_ajax_livesearch.asp The way it transfers the input value via AJAX to a php file for comparison is quite interesting ...

Modifying multiple objects with Vue's V-Model

When utilizing the mounted function in Vue to assign two different objects in the data area and bind one of them to a form, an unusual issue arises: Both objects change when input values are entered in the form For example: <template> <v-card ...