Home > Mobile >  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

Time:10-04

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

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>
))}
)

CodePudding user response:

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),
});
  • Related