This content originally appeared on DEV Community and was authored by Saleh Mubashar
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!
This content originally appeared on DEV Community and was authored by Saleh Mubashar
Saleh Mubashar | Sciencx (2023-03-14T20:12:34+00:00) React and Firestore Part 2. Retrieved from https://www.scien.cx/2023/03/14/react-and-firestore-part-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.