How to update documents in Firebase Firestore and Nextjs14

In this article, we will learn how to update documents in Firebase Firestore and Nextjs14 using server action

Video Tutorial

I have created a video tutorial which is a part of my Next.js 14 Firestore series on YouTube. You can watch the video tutorial for a better understanding of the topic.

{% youtube L4SOb0Uh3OE %}

Create a new server action

1const updatePost = async (postId, formData) => {
2 const docRef = doc(db, 'posts', postId)
3
4 await updateDoc(docRef, {
5 title: formData.get('title'),
6 content: formData.get('content'),
7 tags: formData
8 .get('tags')
9 .split(',')
10 .map(tag => tag.trim()),
11 })
12}

Explanation:

  1. We are creating a new server action called updatePost which takes two parameters postId and formData.
  2. Creating a reference to the document we want to update using doc method.
  3. Updating the document using updateDoc method.
  4. We are getting the data from the form using formData.get method.
  5. You only need to pass the fields you want to update.

Usage

We will use the server action with a form.

1const Form = () => {
2 const id = 'your-post-id'
3
4 return (
5 <form action={updatePost.bind(null, id)}>
6 {/* inputs */}
7 <button type='submit' w='100%'>
8 Submit
9 </button>
10 </form>
11 )
12}

Explanation:

  1. Pass the server action to the form action.
  2. You can get the post id from the URL or any other way.
  3. To pass multiple parameters to the server action, you can use bind method. First parameter is null and the second parameter is the postId.

Update array fields

1const updateData = {
2 tags: arrayUnion('new-tag'),
3 tags: arrayRemove('new-tag'),
4}

Explanation:

  1. arrayUnion is used to add an item to an array field.
  2. arrayRemove is used to remove an item from an array field.

That's it. You can check my entire video series on Firebase Firestore and Next.js 14 on YouTube. Consider subscribing to my channel for more such content.

Shameless Plug

I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Previous PostuseFormStatus basics tutorial | Everything you need to know
Next PostHow to upload images or files on Firebase Cloud Storage with Nextjs 14