0% found this document useful (0 votes)
8 views6 pages

MERN Stack Code Examples and Notes

The document provides code examples for building a full-stack application using the MERN stack, including a React TODO app for the frontend and a Node/Express API with MongoDB for the backend. It includes detailed code snippets for package.json files, server setup, and component structures for both the TODO and Notes applications. Additionally, it outlines steps for running the applications locally and managing data storage with localStorage and MongoDB.

Uploaded by

rajupass13101
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

MERN Stack Code Examples and Notes

The document provides code examples for building a full-stack application using the MERN stack, including a React TODO app for the frontend and a Node/Express API with MongoDB for the backend. It includes detailed code snippets for package.json files, server setup, and component structures for both the TODO and Notes applications. Additionally, it outlines steps for running the applications locally and managing data storage with localStorage and MongoDB.

Uploaded by

rajupass13101
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MERN Practical Rounds - Code Examples

FRONTEND - React TODO App


// [Link]
{
"name": "todo-react",
"version": "1.0.0",
"private": true,
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build"
}
}

// src/[Link]
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './[Link]';

const root = [Link]([Link]('root'));


[Link](<App />);

// src/[Link]
import React, { useState, useEffect } from 'react';

function App() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState('');

// Load from localStorage or fetch sample todos


useEffect(() => {
const saved = [Link]('todos_v1');
if (saved) {
setTodos([Link](saved));
} else {
fetch('[Link]
.then(res => [Link]())
.then(data => {
const list = [Link](t => ({ id: [Link], title: [Link], completed: [Link] }));
setTodos(list);
[Link]('todos_v1', [Link](list));
});
}
}, []);

useEffect(() => {
[Link]('todos_v1', [Link](todos));
}, [todos]);
function addTodo() {
if (![Link]()) return;
const newTodo = { id: [Link](), title: [Link](), completed: false };
setTodos([newTodo, ...todos]);
setText('');
}

function toggle(id) {
setTodos([Link](t => [Link] === id ? { ...t, completed: ![Link] } : t));
}

function remove(id) {
setTodos([Link](t => [Link] !== id));
}

return (
<div className="container">
<h1>TODO App</h1>
<div className="input-row">
<input value={text} onChange={e => setText([Link])} placeholder="Add todo..." />
<button onClick={addTodo}>Add</button>
</div>
<ul className="todo-list">
{[Link](t => (
<li key={[Link]} className={[Link] ? 'done' : ''}>
<span onClick={() => toggle([Link])}>{[Link]}</span>
<button className="del" onClick={() => remove([Link])}>Delete</button>
</li>
))}
</ul>
</div>
);
}

export default App;

// src/[Link]
body { font-family: Arial, sans-serif; background:#f5f7fb; }
.container { max-width:640px; margin:32px auto; background:white; padding:20px; border-radius:8px;
box-shadow:0 2px 8px rgba(0,0,0,0.05); }
.input-row { display:flex; gap:8px; margin-bottom:12px; }
.input-row input { flex:1; padding:8px; border:1px solid #ddd; border-radius:4px; }
.input-row button { padding:8px 12px; border:none; background:#1976d2; color:white; border-
radius:4px; cursor:pointer; }
.todo-list { list-style:none; padding:0; margin:0; }
.todo-list li { display:flex; justify-content:space-between; padding:8px 0; border-bottom:1px solid
#eee; }
.todo-list [Link] span { text-decoration:line-through; color:#888; }
.todo-list .del { background:#e53935; color:white; border:none; padding:6px 8px; border-radius:4px;
cursor:pointer; }

BACKEND - Node/Express + MongoDB Product API


// [Link]
{
"name": "product-api",
"version": "1.0.0",
"main": "[Link]",
"scripts": {
"start": "node [Link]",
"dev": "nodemon [Link]"
},
"dependencies": {
"express": "^4.18.2",
"mongoose": "^7.0.0",
"cors": "^2.8.5",
"dotenv": "^16.0.0"
}
}

// [Link]
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const Product = require('./models/Product');

const app = express();


[Link](cors());
[Link]([Link]());

const PORT = [Link] || 5000;


const MONGO_URI = [Link].MONGO_URI || 'mongodb://localhost:27017/mern_demo';

[Link](MONGO_URI)
.then(() => [Link]('MongoDB connected'))
.catch(err => [Link](err));

// Routes
[Link]('/products', async (req, res) => {
try {
const { name, price, description } = [Link];
const prod = new Product({ name, price, description });
await [Link]();
[Link](201).json(prod);
} catch (err) {
[Link](400).json({ error: [Link] });
}
});

[Link]('/products', async (req, res) => {


const prods = await [Link]().sort({ createdAt: -1 });
[Link](prods);
});

[Link]('/products/:id', async (req, res) => {


const prod = await [Link]([Link]);
if (!prod) return [Link](404).json({ error: 'Not found' });
[Link](prod);
});

[Link]('/products/:id', async (req, res) => {


try {
const updated = await [Link]([Link], [Link], { new: true,
runValidators: true });
if (!updated) return [Link](404).json({ error: 'Not found' });
[Link](updated);
} catch (err) {
[Link](400).json({ error: [Link] });
}
});

[Link]('/products/:id', async (req, res) => {


await [Link]([Link]);
[Link](204).end();
});

[Link](PORT, () => [Link]('Server running on port', PORT));

// models/[Link]
const mongoose = require('mongoose');

const productSchema = new [Link]({


name: { type: String, required: true, trim: true },
price: { type: Number, required: true, min: 0 },
description: { type: String, default: '' }
}, { timestamps: true });

[Link] = [Link]('Product', productSchema);

// .env (example)
# MONGO_URI=mongodb+srv://user:password@[Link]/mern_demo
# PORT=5000

FULL-STACK - Notes App (React frontend + Express backend)


--- Backend (notes-api) ---
// [Link]
{
"name": "notes-api",
"version": "1.0.0",
"main": "[Link]",
"scripts": { "start": "node [Link]", "dev": "nodemon [Link]" },
"dependencies": { "express":"^4.18.2", "mongoose":"^7.0.0", "cors":"^2.8.5", "dotenv":"^16.0.0" }
}

// [Link]
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const Note = require('./models/Note');

const app = express();


[Link](cors());
[Link]([Link]());

[Link]([Link].MONGO_URI || 'mongodb://localhost:27017/notes_demo')
.then(()=>[Link]('Mongo connected')).catch([Link]);
[Link]('/notes', async (req, res) => {
const notes = await [Link]().sort({ createdAt: -1 });
[Link](notes);
});

[Link]('/notes', async (req, res) => {


try {
const note = new Note([Link]);
await [Link]();
[Link](201).json(note);
} catch (err) {
[Link](400).json({ error: [Link] });
}
});

[Link]('/notes/:id', async (req, res) => {


await [Link]([Link]);
[Link](204).end();
});

[Link]([Link] || 4000, ()=>[Link]('Notes API running'));

// models/[Link]
const mongoose = require('mongoose');
const schema = new [Link]({
title: { type: String, required: true },
body: String
}, { timestamps: true });
[Link] = [Link]('Note', schema);

--- Frontend (notes-react) ---


// [Link] similar to earlier React example

// src/[Link] (simplified)
import React, { useEffect, useState } from 'react';

function App() {
const [notes, setNotes] = useState([]);
const [title, setTitle] = useState('');
const [body, setBody] = useState('');

const API = '[Link]

useEffect(() => {
fetch(API + '/notes')
.then(r => [Link]())
.then(setNotes);
}, []);

async function addNote(e) {


[Link]();
const res = await fetch(API + '/notes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: [Link]({ title, body })
});
const newNote = await [Link]();
setNotes([newNote, ...notes]);
setTitle(''); setBody('');
}

async function del(id) {


await fetch(API + '/notes/' + id, { method: 'DELETE' });
setNotes([Link](n => n._id !== id));
}

return (
<div className="container">
<h1>Notes App</h1>
<form onSubmit={addNote}>
<input value={title} onChange={e=>setTitle([Link])} placeholder="Title" required />
<textarea value={body} onChange={e=>setBody([Link])} placeholder="Body" />
<button>Add Note</button>
</form>
<ul>
{[Link](n=>(
<li key={n._id}>
<h4>{[Link]}</h4>
<p>{[Link]}</p>
<button onClick={()=>del(n._id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}

export default App;

--- Notes on running locally ---


1. Backend: set MONGO_URI in .env or use local MongoDB. Run `npm install`, then `npm run dev` (with
nodemon) or `npm start`.
2. Frontend: create-react-app or vite. Replace src/[Link] with code above. Run `npm install` then
`npm start`.
3. Test integration: frontend fetches API on localhost:4000 (CORS enabled).

You might also like