Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to update a field inside a document in Firestore from ReactJS

I am trying to update a field inside a document in firestore from reactjs and its showing an error, even though others did it and it worked for them.

my code

error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

app.js

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
export { auth, app, db };

postpage.js

import { auth, app, db } from "../../firebase/config";
import { collection,  getDocs,  addDoc,  deleteDoc,  doc, updateDoc } from "firebase/firestore";

const [allPosts, setPosts] = useState([]);

 const likePost = async (id, likes) => {
 await updateDoc(doc(db, "posts", id), {
   likes: likes + 1,
 });
};

  const getPosts = async () => {
   const data = await getDocs(postsControllerRef);
   setPosts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id 
  })));
  setLoading(false);
 };

return(
{allposts.map((post, index) => (
 <button 
  onClick={() =>
   likePost(post.postid, post.likes)
  }
 >Like</button>
))}
)

>Solution :

The id is a number but doc() function takes only string path segments. Also, you must pass the documentId to update a specific document. Try changing the following line:

onClick={() =>
 likePost(post.id, post.likes) // pass .id and not .postid
}

If postid is the document ID itself, then try:

const likePost = async (id, likes) => {
  await updateDoc(doc(db, "posts", String(id)), {
    likes: likes + 1,
  });
}; 

Also, as @FrankVanPuffelen commented, you can use increment() instead as shown below:

import { increment } from "firebase/firestore"

await updateDoc(doc(db, "posts", String(id)), {
  likes: increment(1),
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading