CodeWithYou

Crafting a Full-Stack To-Do Application with MERN: A Comprehensive Guide

Published on
Authors
"Crafting a Full-Stack To-Do Application with MERN: A Comprehensive Guide"
Photo by AI

Crafting a Full-Stack To-Do Application with MERN: A Comprehensive Guide

Welcome to this in-depth guide where we’ll walk you through creating a fully functional To-Do application using the MERN stack. MERN stands for MongoDB, Express.js, React, and Node.js, a popular combo for modern web development. Throughout this guide, we'll cover everything from setting your environment to implementing core functionalities of a To-Do app, including Create, Read, Update, and Delete (CRUD) operations. We will also integrate it with MongoDB Atlas, a free cloud database service.

Prerequisites

Before diving into the development process, it's essential to have a fundamental understanding of HTML, CSS, and JavaScript. Familiarity with frontend and backend frameworks and libraries will greatly help. This guide focuses primarily on functionality; therefore, you are encouraged to customize the design to match your preferences.

Table of Contents

Introduction to the MERN Stack

The MERN stack is a powerful set of technologies for building web applications using JavaScript throughout the entire stack. Here's a quick look at its components:

  • MongoDB: A NoSQL database that stores data in a JSON-like format.
  • Express.js: A minimal and flexible Node.js web application framework, providing a robust set of features for web and mobile applications.
  • React: A JavaScript library for building user interfaces, allowing functional and component-driven programming techniques.
  • Node.js: A JavaScript runtime environment that executes JavaScript code server-side.

Setting Up Your Development Environment

To get started, you must install Node.js and npm (Node Package Manager). Instead of installing Node.js in individual project directories, install it globally so it can be accessed across different projects.

  1. Download and install Node.js from the official website.
  2. To verify the installation, open your command line and execute the following commands:
    node -v
    npm -v
    
    This will display the installed versions of Node.js and npm.

Creating a New MERN Project

Let's set up a new directory for our MERN To-Do app:

mkdir mern-todo-app
cd mern-todo-app
code .

This opens the project directory in Visual Studio Code, where we will write our application.

Frontend Setup

Set Up Vite with React and TypeScript

Navigate to your project root and create a React application using Vite:

npm create vite@latest frontend --template react-ts

This command initializes a TypeScript React project within the frontend folder of your mern-todo-app directory.

Install Axios for Making API Requests

Axios is a popular library used for making HTTP requests. It simplifies the process of sending requests to our backend API. To install Axios, execute:

cd frontend
npm install axios

Build the To-Do App UI

Now, we’ll create the user interface for our To-Do application. Inside the src folder, create an App.tsx file and populate it with the following:

// Importing necessary dependencies
import React, { useState, useEffect } from "react";
import axios from "axios";
import TodoList from "./components/TodoList.tsx";
import "./App.css";

// Defining the Task interface
interface Task {
  _id: string;
  title: string;
  completed: boolean;
}

const App: React.FC = () => {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [task, setTask] = useState<string>(""
  const [editingTaskId, setEditingTaskId] = useState<string | null>(null);
  const [editingTitle, setEditingTitle] = useState<string>("");

  useEffect(() => {
    const fetchTasks = async () => {
      try {
        const response = await axios.get<Task[]>(`http://localhost:5000/api/tasks`);
        setTasks(response.data);
      } catch (error) {
        console.error("Error fetching tasks:", error);
      }
    };
    fetchTasks();
  }, []);

  const addTask = async () => {
    // Add task implementation...
  };
  const deleteTask = async (id: string) => {
    // Delete task implementation...
  };
  const updateTask = async (id: string, updatedTask: Partial<Task>) => {
    // Update task implementation...
  };
  // Add more logic as required for editing and rendering UI...
};

export default App;

Here’s a step-by-step breakdown of the key processes in the component:

  • Fetching Tasks: When the component mounts, it fetches tasks from the backend using the useEffect hook.
  • Adding Tasks: Implement functions that allow users to add tasks.
  • Editing and Deleting Tasks: Implement logic for editing and deleting tasks as needed.

Backend Setup

In the mern-todo-app directory, create a backend folder. Within it, run:

mkdir backend
cd backend
npm init -y

This initializes a Node.js server.

Install Required Packages

Run:

npm install express mongoose dotenv cors

Each package has its purpose:

  • Express: Framework for handling server-side logic.
  • Mongoose: Simplifies interactions with the MongoDB database.
  • Dotenv: Loads environment variables from a .env file.
  • CORS: Facilitates cross-origin resource sharing.

Create a server.js File

Inside your backend folder, create a server.js file:

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const dotenv = require("dotenv");

dotenv.config();
const app = express();
app.use(cors());
app.use(express.json());

const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGO_URI);
    console.log("MongoDB Connected");
  } catch (err) {
    console.error("MongoDB Connection Failed:", err);
    process.exit(1);
  }
};
connectDB();

app.use("/api/tasks", require('./routes/tasks'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Define Task Model

Create a model folder and add Task.js:

const mongoose = require("mongoose");
const TaskSchema = new mongoose.Schema({
    title: { type: String, required: true },
    completed: { type: Boolean, default: false },
});
module.exports = mongoose.model("Task", TaskSchema);

Define Routes

Interior routes folder, create tasks.js to manage routes for CRUD operations.

Create a .env File

Inside the backend folder, create and configure a .env file:

MONGO_URI=your_mongodb_atlas_uri

This will contain your MongoDB Atlas URI for database connectivity.

Set Up MongoDB Atlas

Register on MongoDB Atlas, create a cluster, whitelist your IP, and note the database connection string for your .env file.

Running the Application

To run both the frontend and backend efficiently, install concurrently:

npm install concurrently

Configure your package.json to manage startup scripts:

{
  "scripts": {
    "start": "cd backend && node server.js",
    "client": "cd frontend && npm run dev",
    "dev": "concurrently \"npm run start\" \"npm run client\""
  }
}

Now you can run the application with:

npm run dev

Conclusion

Congratulations! You’ve just built a functional MERN To-Do app! This project serves as a robust foundation for enhancing your application. You can further add features like user authentication, due dates, categorization of tasks, or deploy it to a cloud hosting platform. Don’t forget to customize the styling to match your personal branding!

If you found this guide insightful and beneficial, sharing it would be greatly appreciated. Happy coding!

For additional learning resources and documentation, check out:

Advertisement