Building a Dynamic Web App with MERN Stack: A Complete CRUD Guide

Introduction:The world of web development is constantly evolving, and MERN (MongoDB, Express.js, React.js, Node.js) stack has emerged as a powerful combination for building robust and dynamic web applications. In this tech blog, we'll dive deep into the MERN stack and walk you through the process of creating a fully functional CRUD (Create, Read, Update, Delete) application. By the end of this guide, you'll have a strong grasp of MERN development and be well-equipped to tackle your own projects.

In this blog, I will explain to you a MERN CRUD application example. We will create a MERN CRUD application for beginners. I will give you a very simple example of how to create CRUD in MERN. At the end of this blog you will learn a CRUD application in MERN.

So, let's follow a few steps to create an example of MERN CRUD application tutorial.

First, let's start with the backend code using Express.js and Node.js.

 $ npm install express mongoose

1. Create a file named server.js:


const express = require('express');
const mongoose = require('mongoose');
const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.log(err));

// Create a schema for the data model
const itemSchema = new mongoose.Schema({
  name: String,
  description: String,
});

// Create a model based on the schema
const Item = mongoose.model('Item', itemSchema);

// Set up middleware
app.use(express.json());

// Routes

// Get all items
app.get('/items', (req, res) => {
  Item.find({}, (err, items) => {
    if (err) {
      console.log(err);
      res.status(500).send('An error occurred');
    } else {
      res.json(items);
    }
  });
});

// Get a specific item
app.get('/items/:id', (req, res) => {
  Item.findById(req.params.id, (err, item) => {
    if (err) {
      console.log(err);
      res.status(500).send('An error occurred');
    } else if (!item) {
      res.status(404).send('Item not found');
    } else {
      res.json(item);
    }
  });
});

// Create a new item
app.post('/items', (req, res) => {
  const newItem = new Item(req.body);
  newItem.save((err, item) => {
    if (err) {
      console.log(err);
      res.status(500).send('An error occurred');
    } else {
      res.status(201).json(item);
    }
  });
});

// Update an existing item
app.put('/items/:id', (req, res) => {
  Item.findByIdAndUpdate(req.params.id, req.body, { new: true }, (err, item) => {
    if (err) {
      console.log(err);
      res.status(500).send('An error occurred');
    } else if (!item) {
      res.status(404).send('Item not found');
    } else {
      res.json(item);
    }
  });
});

// Delete an item
app.delete('/items/:id', (req, res) => {
  Item.findByIdAndRemove(req.params.id, (err, item) => {
    if (err) {
      console.log(err);
      res.status(500).send('An error occurred');
    } else if (!item) {
      res.status(404).send('Item not found');
    } else {
      res.sendStatus(204);
    }
  });
});

// Start the server
app.listen(5000, () => {
  console.log('Server is running on port 5000');
});

Now, let's move on to the frontend code using React.js.

2. Create a new React app:

 $ npx create-react-app frontend
 $ cd frontend

3. Install required packages:

$ npm install axios

4. Replace the content of src/App.js with the following code:


import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [items, setItems] = useState([]);
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');

  useEffect(() => {
    fetchItems();
  }, []);

  const fetchItems = async () => {
    try {
      const response = await axios.get('/items');
      setItems(response.data);
    } catch (error) {
      console.log(error);
    }
  };

  const addItem = async () => {
    try {
      const response = await axios.post('/items', { name, description });
      setItems([...items, response.data]);
      setName('');
      setDescription('');
    } catch (error) {
      console.log(error);
    }
  };

  const deleteItem = async (id) => {
    try {
      await axios.delete(`/items/${id}`);
      setItems(items.filter(item => item._id !== id));
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div>
      <h1>Items</h1>
      <ul>
        {items.map(item => (
          <li key={item._id}>
            {item.name} - {item.description}
            <button onClick={() => deleteItem(item._id)}>Delete</button>
          </li>
        ))}
      </ul>
      <h2>Add Item</h2>
      <form onSubmit={addItem}>
        <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="Name" required />
        <input type="text" value={description} onChange={e => setDescription(e.target.value)} placeholder="Description" required />
        <button type="submit">Add</button>
      </form>
    </div>
  );

}

export default App;

5. Finally, start the frontend development server:

$ npm start

The backend server will be running on http://localhost:5000, and the React development server will be running on http://localhost:3000. You can now access the application in your web browser and perform CRUD operations on the items.

Note: Make sure you have MongoDB installed and running locally on your machine before running the code. You can modify the MongoDB connection URL (mongodb://localhost/mydatabase) in the backend code if needed.

Remember to adjust the code as per your specific requirements, including database configurations and front-end design.