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'
4
5const 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)
12
13 return Timestamp.fromDate(randomDate)
14}
15
16const addMultiplePosts = async () => {
17 const batch = writeBatch(db)
18
19 posts.forEach(post => {
20 const postData = {
21 ...post,
22 createdAt: getRandomTimestamp(),
23 }
24
25 const docRef = doc(collection(db, 'posts'))
26 batch.set(docRef, postData)
27 })
28
29 await batch.commit()
30}

Explanation:

  1. We have created a new batch using writeBatch from firebase/firestore
  2. I have added a posts.json file in the data folder which contains an array of posts. You can add your own data. Or use this
  3. We are iterating through the posts array and creating a new document reference for each post using doc 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 a getRandomTimestamp function to get a random timestamp between 2024 and the current date.
  4. We are adding the document reference and the post data to the batch using batch.set function.
  5. 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:

  1. 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.
  2. We have created a button to add multiple posts. When the button is clicked, the addMultiplePosts function will be called.
  3. 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

Blogs you might want to read:

Videos might you might want to watch:

Previous PostHow to get documents from Firebase Firestore in Nextjs14
Next PostRadix UI crash course