How to add multiple documents to firestore from Nextjs14
In this article, we will learn how to add multiple documents to firestore using server actions in Nextjs14. You can check my previous blog on how to add single documents from here
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 05uvGfzm5hE %}
Firestore batch
Firestore batch is a feature that allows you to perform multiple write operations as a single unit. This is useful when you want to add multiple documents to firestore. You can use the batch to add, update, or delete multiple documents in a single batch. If any of the operations fail, the entire batch fails and no changes are made to the database. You can use Transactions to perform both read and write operations in a single batch. You can read more about transactions here
Create a new server action
1import posts from '@/data/posts'2import { writeBatch, doc, collection } from 'firebase/firestore'3import { db } from '@/config/firebase'45const getRandomTimestamp = () => {6 const startTimestamp = new Date('2024-01-01').getTime()7 const endTimestamp = new Date().getTime()8 const randomTimestamp = Math.floor(9 Math.random() * (endTimestamp - startTimestamp + 1) + startTimestamp,10 )11 const randomDate = new Date(randomTimestamp)1213 return Timestamp.fromDate(randomDate)14}1516const addMultiplePosts = async () => {17 const batch = writeBatch(db)1819 posts.forEach(post => {20 const postData = {21 ...post,22 createdAt: getRandomTimestamp(),23 }2425 const docRef = doc(collection(db, 'posts'))26 batch.set(docRef, postData)27 })2829 await batch.commit()30}
Explanation:
- We have created a new batch using
writeBatch
fromfirebase/firestore
- I have added a
posts.json
file in thedata
folder which contains an array of posts. You can add your own data. Or use this - We are iterating through the
posts
array and creating a new document reference for each post usingdoc
function.- We are also adding a
createdAt
field with a random timestamp. - You can use
ServerTimeStamp
function to add the current timestamp. But you will get the same timestamp for all the documents. So I have created agetRandomTimestamp
function to get a random timestamp between 2024 and the current date.
- We are also adding a
- We are adding the document reference and the post data to the batch using
batch.set
function. - Finally, we are committing the batch using
batch.commit
function.
Use the server action with a event handler
1'use client'2const AddPostForm = () => (3 <>4 <form action={addPost}>5 {/* Some input components */}6 <Button type='submit'>Submit</Button>7 </form>8 <Button onClick={() => addMultiplePosts()}>Add Multiple Posts</Button>9 </>10)
Explanation:
- To use an event handler, we need a client component. However, you can create a seperate component for the button and make that a client component.
- We have created a button to add multiple posts. When the button is clicked, the
addMultiplePosts
function will be called. - Make sure to don't pass the server action directly to the onClick event. You need to wrap it inside an arrow function. Otherwise, you will get an error.
That's it. You have successfully added multiple documents to firestore using server actions in Nextjs14. Checkout my other video tutorials on Next.js 14 Firestore series on YouTube.
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: