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)34 await updateDoc(docRef, {5 title: formData.get('title'),6 content: formData.get('content'),7 tags: formData8 .get('tags')9 .split(',')10 .map(tag => tag.trim()),11 })12}
Explanation:
- We are creating a new server action called
updatePost
which takes two parameterspostId
andformData
. - Creating a reference to the document we want to update using
doc
method. - Updating the document using
updateDoc
method. - We are getting the data from the form using
formData.get
method. - 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'34 return (5 <form action={updatePost.bind(null, id)}>6 {/* inputs */}7 <button type='submit' w='100%'>8 Submit9 </button>10 </form>11 )12}
Explanation:
- Pass the server action to the form action.
- You can get the post id from the URL or any other way.
- To pass multiple parameters to the server action, you can use
bind
method. First parameter isnull
and the second parameter is thepostId
.
Update array fields
1const updateData = {2 tags: arrayUnion('new-tag'),3 tags: arrayRemove('new-tag'),4}
Explanation:
arrayUnion
is used to add an item to an array field.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
- Email: thatanjan@gmail.com
- LinkedIn: @thatanjan
- Portfolio: anjan
- Github: @thatanjan
- Instagram : @thatanjan
- Twitter: @thatanjan
Blogs you might want to read:
- Eslint, prettier setup with TypeScript and react
- What is Client-Side Rendering?
- What is Server Side Rendering?
- Everything you need to know about tree data structure
- 13 reasons why you should use Nextjs
- Beginners guide to quantum computers
Videos might you might want to watch: