Hello guys!
In the previous tutorial, Part 1, we learned how to save and get data from Firestore, which is a cloud-hosted, Firebase NoSQL database. We also learned how to create and integrate a Firestore database to React.
In this part 2, we will learn how to update, delete and sort data.
You can read the detailed version of this article here:
Updating Documents in Firestore
In your React file, let's say App.js, import the database from the firebase.js file. Next, get the collection (we will call it "users") and check whether the document you want to update exists or not.
If it does exist, we can update it exists using the update method. We will provide this method an object that will contain the name attribute and its updated value.
import React from "react";
import db from "./firebase";
function App() {
const getData = async () => {
//get the user
const user = db.collection("users").doc("user1");
const doc = await user.get();
//check if user exists
if (doc.exists) {
//if user exists, update the name
await user.update({ username: "Mike" });
} else {
console.log("User does not exist!");
}
};
getData();
return <div className="app"></div>;
}
export default App;
Deleting Documents in Firestore
Once again, we will check if the document exists and if it does, we will delete the document using the simple delete method.
if (doc.exists) {
//if user exists we delete it
await user.delete()
} else {
console.log("User does not exist!");
}
Sorting
Detailed information on sorting which includes Getting a List of Documents and Sorting based on a specific attribute is discussed in the detailed article. Check it out:
Thanks for Reading!
Check out my personal blog too
Top comments (0)