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.

Perform CRUD Operations

Setup

  1. Create a React component file named db-test with the path /db.

  2. Add buttons for CRUD operations: Add Product, Get Product, Update Product and Delete Product.

db-test.tsx
import React from "react"
import { Button } from "antd"

export default function Component(props: any) {
    return (
        <div>
            <Button>Add Product</Button>
            <Button>Get Product</Button>
            <Button>Update Product</Button>
            <Button>Delete Product</Button>
        </div>
    )
}
Expand for Tailwind styled code.
db-test.tsx
import React from "react"
import { Button } from "antd"

export default function Component(props: any) {
  return (
    <div className="h-screen flex items-center justify-center">
      <Button className="text-xl w-60 h-14">
        Add Product
      </Button>
      <Button className="text-xl w-60 h-14">
        Get Product
      </Button>
      <Button className="text-xl w-60 h-14">
        Update Product
      </Button>
      <Button className="text-xl w-60 h-14">
        Delete Product
      </Button>
    </div>
  )
}

Create

Backend Configuration

  1. Create a backend file named add within the main-features folder.

  2. Import the data function from magicjs.dev/backend.

  3. Use data() to connect to MongoDB and specify the collection name as 'products'.

  4. Utilize MongoDB's functions to add products, such as insertOne().

Refer the snippet below.

add.server.tsx
import { createBackendFunction, data } from "@magicjs.dev/backend"

export default createBackendFunction(async function (name: string) {

    await data('products').insertOne({
        name
    })

    return "Message from server"
})

Frontend Configuration

  1. Import addServer into the frontend component.

  2. Call addServer in the onClick event of the Add Product button to trigger an alert indicating successful addition.

Refer the snippet below.

db-test.tsx
import React from "react"
import { Button } from "antd"
import addServer from "./add.server"

export default function Component(props: any) {
    return (
        <div>
            <Button onClick={() => addServer('Rubiks Cube').then(() => alert('Added'))}>
                Add Product
            </Button>
            <Button>Get Product</Button>
            <Button>Update Product</Button>
            <Button>Delete Product</Button>
        </div>
    )
}

Read

Backend Configuration

  1. Create a backend file named list.

  2. Import data and fetch all products using find().toArray().

  3. Return the list of products.

Refer the snippet below.

list.server.tsx
import { createBackendFunction, data } from "@magicjs.dev/backend"

export default createBackendFunction(async function () {

  const allProducts = await data('products').find().toArray()

  return allProducts
})

Frontend Configuration

  1. Import listServer into the frontend component.

  2. 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.

<Button
    onClick={() => listServer()
        .then((allProducts) => alert(allProducts.map((p) => p.name)
            .join(', ')))}>
    Get Product
</Button>

Update

Backend Configuration

  1. Create a backend file named update.

  2. Import data and utilize updateOne() to modify product details.

  3. Pass both the old and new names of the product to be updated.

Refer the snippet below.

udpate.server.tsx
import { createBackendFunction, data } from "@magicjs.dev/backend"

export default createBackendFunction(async function (name: string, newName: string,) {
    data("products").updateOne({ name },
        {
            $set: {
                name: newName,
            },
        },
    )

    return "Message from server"
})

Frontend

  1. Import updateServer into the frontend component.

  2. Call updateServer in the onClick event of the Update Product button, triggering an alert upon successful update.

Refer the snippet below.

<Button
    onClick={() => updateServer('Rubiks Cube', 'Water Bottle')
        .then(() => alert("Updated"))}>
    Update Product
</Button>

Delete

Backend Configuration

  1. Create a backend file named delete.

  2. Import data and use deleteOne() to remove a product based on specified criteria.

Refer the snippet below.

import { createBackendFunction, data } from "@magicjs.dev/backend"

export default createBackendFunction(async function (name: string) {
    await data('products').deleteOne({ name })

    return "Message from server"
})

Frontend Configuration

  1. Import deleteServer into the frontend component.

  2. Call updateServer in the onClick event of the Delete Product button, triggering an alert upon successful deletion.

Refer the snippet below.

<Button
    onClick={() => deleteServer('Water Bottle')
        .then(() => alert('Deleted'))}>
    Delete Product
</Button>

Access MongoDB database

  1. Click the Connect to Database button in the bottom section.

  2. Click the Launch MongoDB Express button.

  3. 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