Perform CRUD Operations
In this tutorial, we will explore how to perform CRUD (Create, Read, Update, Delete) operations using MagicJS, enabling seamless interaction with a backend database.
Setup
Create a React component file named
db-test
with the path/db
.Add buttons for CRUD operations: Add Product, Get Product, Update Product and Delete Product.
Create
Backend Configuration
Create a backend file named
add
within themain-features
folder.Import the
data
function frommagicjs.dev/backend
.Use
data()
to connect to MongoDB and specify the collection name as 'products
'.Utilize MongoDB's functions to add products, such as
insertOne()
.
Refer the snippet below.
Frontend Configuration
Import
addServer
into the frontend component.Call
addServer
in the onClick event of the Add Product button to trigger an alert indicating successful addition.
Refer the snippet below.
Read
Backend Configuration
Create a backend file named
list
.Import
data
and fetch all products usingfind().toArray()
.Return the list of products.
Refer the snippet below.
Frontend Configuration
Import
listServer
into the frontend component.Call
listServer
in the onClick event of the Get Product button, displaying an alert with a comma-separated list of product names upon clicking.
Refer the snippet below.
Update
Backend Configuration
Create a backend file named
update
.Import
data
and utilizeupdateOne()
to modify product details.Pass both the old and new names of the product to be updated.
Refer the snippet below.
Frontend
Import
updateServer
into the frontend component.Call
updateServer
in the onClick event of the Update Product button, triggering an alert upon successful update.
Refer the snippet below.
Delete
Backend Configuration
Create a backend file named
delete
.Import
data
and usedeleteOne()
to remove a product based on specified criteria.
Refer the snippet below.
Frontend Configuration
Import
deleteServer
into the frontend component.Call
updateServer
in the onClick event of the Delete Product button, triggering an alert upon successful deletion.
Refer the snippet below.
Access MongoDB database
Click the Connect to Database button in the bottom section.
Click the Launch MongoDB Express button.
Login with the provided credentials.
Once logged in, you will be able to view and interact with the database.
🎉 Congratulations! You have successfully implemented CRUD operations using MagicJS, enabling seamless interaction with a backend database.
By mastering these techniques, you can create dynamic and responsive applications with robust data management capabilities. Experiment with different functionalities to enhance your web development projects further.
Last updated