📅  最后修改于: 2023-12-03 15:19:43.140000             🧑  作者: Mango
In this guide, we will learn how to use React and Firebase to add a document to a collection in a Firestore database using JavaScript.
Before proceeding, make sure you have the following installed:
Also, create a Firebase project and initialize Firestore in your project. Refer to the official Firebase documentation for detailed instructions.
Assuming you have set up your React app and Firebase project, let's install the necessary Firebase dependencies in your project:
$ npm install firebase
Next, import Firebase in your JavaScript file:
import firebase from 'firebase/app';
import 'firebase/firestore';
Initialize Firebase in your app by adding the following code snippet inside your component's componentDidMount
or useEffect
hook:
componentDidMount() {
const firebaseConfig = {
// Add your Firebase project configuration here
};
firebase.initializeApp(firebaseConfig);
this.db = firebase.firestore();
}
To add a document to a collection in Firebase Firestore, use the add
method provided by the Firestore CollectionReference
.
Here's an example of how to add a document to a collection called users
:
addUser = () => {
this.db.collection('users').add({
name: 'John Doe',
email: 'john@example.com',
age: 25
})
.then((docRef) => {
console.log('Document written with ID: ', docRef.id);
})
.catch((error) => {
console.error('Error adding document: ', error);
});
}
The add
method returns a Promise
that resolves to a DocumentReference
once the document is successfully written to the collection. You can use the docRef.id
to retrieve the automatically generated unique ID assigned to the new document.
In this guide, we've learned how to add a document to a collection in Firebase Firestore using React and JavaScript. Now you can create and add documents to collections in your Firestore database using the Firebase SDK. Happy coding!
Note: Insert your own Firebase project configuration inside the
firebaseConfig
object during initialization.