<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Reshma Shaik</title>
    <description>The latest articles on DEV Community by Reshma Shaik (@shaikr786).</description>
    <link>https://dev.to/shaikr786</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2599059%2F390acddc-faa4-451e-9a9d-53a98d305c44.png</url>
      <title>DEV Community: Reshma Shaik</title>
      <link>https://dev.to/shaikr786</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/shaikr786"/>
    <language>en</language>
    <item>
      <title>Stock Management System - Frontend</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Tue, 08 Apr 2025 00:37:54 +0000</pubDate>
      <link>https://dev.to/shaikr786/stock-management-system-frontend-2e37</link>
      <guid>https://dev.to/shaikr786/stock-management-system-frontend-2e37</guid>
      <description>&lt;p&gt;As we are done with 👉&lt;a href="https://dev.to/shaikr786/common-errors-in-frontened-setup-stock-management-system-2f1e"&gt; auth and private route setup &lt;/a&gt;. Let's continue further to complete frontend part of our project following the below requirements.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fls5l4xg4e8yejd4rgvcq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fls5l4xg4e8yejd4rgvcq.png" alt="Plan" width="723" height="775"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Create a Dashboard page &lt;code&gt;pages/Dashboard.jsx&lt;/code&gt;
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;I wanted a dashboard that provides all my required components are displayed on the screen.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;As, dashboard has to be a private route i.e, after login only user r allowed to access.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Fetching user details from AuthContext.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the user is not available, provides a loading screen.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Displaying a dark-themed dashboard with a Navbar.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Showing a welcome message with user.name.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Providing three navigation links to different sections using a grid layout with appropriate styling.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useContext } from "react";
import { AuthContext } from "../context/AuthContext";
import { Link } from "react-router-dom";
import Navbar from "../components/Navbar";

const Dashboard = () =&amp;gt; {
  const { user } = useContext(AuthContext);

  if (!user) {
    return &amp;lt;div className="h-screen flex justify-center items-center text-white text-lg"&amp;gt;Loading...&amp;lt;/div&amp;gt;;
  }

  return (
    &amp;lt;div className="min-h-screen bg-gray-900 text-white flex flex-col"&amp;gt;
      {/* Navbar */}
      &amp;lt;Navbar /&amp;gt;

      {/* Dashboard Content */}
      &amp;lt;div className="flex-grow flex flex-col items-center justify-center px-6"&amp;gt;
        &amp;lt;h1 className="text-3xl font-semibold mb-4"&amp;gt;Welcome, {user.name}!&amp;lt;/h1&amp;gt;
        &amp;lt;p className="text-gray-400 mb-8"&amp;gt;Manage your stock efficiently with real-time insights.&amp;lt;/p&amp;gt;

        {/* Dashboard Cards */}
        &amp;lt;div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-8 w-full max-w-4xl"&amp;gt;
          &amp;lt;Link to="/products" className="p-6 bg-white/10 backdrop-blur-lg rounded-xl text-center hover:bg-white/20 transition"&amp;gt;
            &amp;lt;h2 className="text-xl font-semibold"&amp;gt;Manage Products&amp;lt;/h2&amp;gt;
          &amp;lt;/Link&amp;gt;
          &amp;lt;Link to="/stock-overview" className="p-6 bg-white/10 backdrop-blur-lg rounded-xl text-center hover:bg-white/20 transition"&amp;gt;
            &amp;lt;h2 className="text-xl font-semibold"&amp;gt;Stock Overview&amp;lt;/h2&amp;gt;
          &amp;lt;/Link&amp;gt;
          &amp;lt;Link to="/analytics" className="p-6 bg-white/10 backdrop-blur-lg rounded-xl text-center hover:bg-white/20 transition"&amp;gt;
            &amp;lt;h2 className="text-xl font-semibold"&amp;gt;Analytics Dashboard&amp;lt;/h2&amp;gt;
          &amp;lt;/Link&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Dashboard;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Let's implement the components that we defined above.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  2. &lt;code&gt;components/ProductManagement.jsx&lt;/code&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Setting up the required imports.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState } from "react"; //for statemanagement and sideeffects.
import { toast } from "react-toastify"; //for notification pop-ups
import { Trash2, Edit3 } from "lucide-react"; //Icons for delete and edit operations.
import api from "../utils/api"; //for api calls.
import Navbar from "./Navbar";  //navbar component
import { useNavigate } from "react-router-dom"; //React router navigation function.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;State Variables&lt;/li&gt;
&lt;li&gt;products: storing the list of products.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;form: Managing product form data for adding/editing.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;sellForm: Storing sales data.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;showAddForm, showSellForm: Toggle forms for adding/selling products.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;editingProduct: Stores the ID of the product being edited.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [products, setProducts] = useState([]);
const [form, setForm] = useState({ name: "", category: "", price: "", quantityInStock: "" });
const [sellForm, setSellForm] = useState({ productId: "", quantity: "" });
const [showAddForm, setShowAddForm] = useState(false);
const [showSellForm, setShowSellForm] = useState(false);
const [editingProduct, setEditingProduct] = useState(null);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Fetching the Products
Fetching the products data when the component loads from the API,then updating the state with API response.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
  fetchProducts();
}, []);

const fetchProducts = async () =&amp;gt; {
  try {
    const { data } = await api.get("/products");
    setProducts(data);
  } catch (error) {
    console.error(error);
    toast.error("Failed to fetch products. Please try again.");
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Handling Input Changes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Updates form state dynamically as user types.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleChange = (e) =&amp;gt; setForm({ ...form, [e.target.name]: e.target.value });

const handleSellChange = (e) =&amp;gt; {
  const { name, value } = e.target;
  setSellForm((prev) =&amp;gt; ({
    ...prev,
    [name]: name === "quantity" ? Number(value) : value, // Ensures quantity is a number
  }));
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Handling the product editing
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleEdit = (product) =&amp;gt; {
  setEditingProduct(product._id); // Store product ID
  setForm({ ...product }); // Populate form with product data
  setShowAddForm(true); // Open form modal
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Adding or updating the products
1.If editingProduct exists → Update product (PUT /products/:id).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2.Else → Create new product (POST /products).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleSubmit = async (e) =&amp;gt; {
  e.preventDefault();
  if (!form.name || !form.category || !form.price || !form.quantityInStock) {
    toast.warn("Please fill in all fields before submitting.");
    return;
  }
  try {
    if (editingProduct) {
      await api.put(`/products/${editingProduct}`, form);
      toast.success("Product updated successfully");
      setEditingProduct(null); 
    } else {
      await api.post("/products", form);
      toast.success("Product added successfully");
    }
    fetchProducts();
    setForm({ name: "", category: "", price: "", quantityInStock: "" });
    setShowAddForm(false);
  } catch (error) {
    toast.error(error.response?.data?.message || "Error adding product.");
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Selling a Product
1.Sends a sale request (POST /sales/sell).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2.Reduces stock count when a product is sold.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleSellSubmit = async (e) =&amp;gt; {
  e.preventDefault();
  if (!sellForm.productId || !sellForm.quantity || sellForm.quantity &amp;lt;= 0) {
    toast.warn("Please select a product and enter a valid quantity.");
    return;
  }
  try {
    await api.post("/sales/sell", sellForm);
    toast.success("Product sold successfully! 💰");
    fetchProducts();
    setSellForm({ productId: "", quantity: "" });
    setShowSellForm(false);
  } catch (error) {
    toast.error(error.response?.data?.message || "Error selling product.");
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Deleting a Product
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleDelete = async (id) =&amp;gt; {
  try {
    await api.delete(`/products/${id}`);
    toast.success("Product deleted successfully! 🗑️");
    fetchProducts();
  } catch (error) {
    console.error(error);
    toast.error("Error deleting product. Please try again.");
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;CSV Import&lt;/li&gt;
&lt;li&gt;Allows users to upload a CSV file.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Sends a multipart/form-data request to /csv/import-csv.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleImportCSV = async (e) =&amp;gt; {
  e.preventDefault();
  const file = e.target.files[0];
  if (!file) {
    toast.warn("Please select a CSV file to import.");
    return;
  }

  const formData = new FormData();
  formData.append("file", file);

  try {
    await api.post("/csv/import-csv", formData, { headers: { "Content-Type": "multipart/form-data" } });
    toast.success("CSV imported successfully! 📂");
    fetchProducts();
  } catch (error) {
    console.error(error);
    toast.error("Error importing CSV. Please check the file format, and duplicates before Import.");
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;CSV Export
1.Fetches CSV data from /csv/export-csv.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2.downloads a file for the user.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleExportCSV = async () =&amp;gt; {
  try {
    const response = await api.get("/csv/export-csv", { responseType: "blob" });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", "products.csv");
    document.body.appendChild(link);
    link.click();
    toast.success("CSV exported successfully! 📤");
  } catch (error) {
    console.error(error);
    toast.error("Error exporting CSV. Please try again.");
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt; Component Structure in return statement.&lt;/li&gt;
&lt;li&gt;Adding new products&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Selling products&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Importing/exporting CSV files&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Editing and deleting products&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Displaying a list of products&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;Header Section
Back to Dashboard button → Navigates back to the dashboard.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Title: "Product Management" → Displays the section title.&lt;/p&gt;

&lt;p&gt;CSV Import &amp;amp; Export → Allows importing a CSV file.&lt;br&gt;
                    → Exports the product list as a CSV.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{/* Header */}
    &amp;lt;div className="flex items-center justify-between mb-6"&amp;gt;
      &amp;lt;button
        onClick={() =&amp;gt; navigate("/dashboard")}
        className="flex items-center gap-2 bg-gray-600 hover:bg-gray-700 text-white py-2 px-4 rounded-lg shadow-md transition duration-300"
      &amp;gt;
        Back to Dashboard
      &amp;lt;/button&amp;gt;
      &amp;lt;h1 className="text-2xl font-bold flex-grow text-center"&amp;gt;Product Management&amp;lt;/h1&amp;gt;
      &amp;lt;div className="flex gap-4"&amp;gt;
        &amp;lt;input type="file" accept=".csv" onChange={handleImportCSV} className="hidden" id="importCSV" /&amp;gt;
        &amp;lt;label htmlFor="importCSV" className="bg-yellow-500 hover:bg-yellow-600 text-white py-2 px-4 rounded cursor-pointer"&amp;gt;Import CSV&amp;lt;/label&amp;gt;
        &amp;lt;button onClick={handleExportCSV} className="bg-purple-500 hover:bg-purple-600 text-white py-2 px-4 rounded"&amp;gt;Export CSV&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Action Buttons
1."Add Product" Button → Toggles the add/edit product form.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2."Sell Product" Button → Toggles the sell product form.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{/* Action Buttons */}
    &amp;lt;div className="flex gap-4 mb-4"&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setShowAddForm(!showAddForm)} className="bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-lg"&amp;gt;
        {showAddForm ? "Close" : "Add Product"}
      &amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setShowSellForm(!showSellForm)} className="bg-yellow-500 hover:bg-yellow-600 text-white py-2 px-4 rounded-lg"&amp;gt;
        {showSellForm ? "Close" : "Sell Product"}
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add/Edit Product form
1.Displays a form when adding a new product or editing an existing one.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2.Fields:Product Name,Category,Price,Stock Quantity&lt;/p&gt;

&lt;p&gt;3.Submit button → Adds or updates the product.&lt;/p&gt;

&lt;p&gt;4.Cancel button → Closes the form and resets the state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{/* Add Product Form */}
    {showAddForm &amp;amp;&amp;amp; (
      &amp;lt;form onSubmit={handleSubmit} className="bg-gray-800 p-6 rounded-xl shadow-lg grid gap-4 w-full max-w-md mx-auto"&amp;gt;
        &amp;lt;h2 className="text-xl font-semibold text-white text-center"&amp;gt;{editingProduct ? "Edit Product" : "Add New Product"}&amp;lt;/h2&amp;gt;
        &amp;lt;input type="text" name="name" placeholder="Product Name" value={form.name} onChange={handleChange} required className="p-3 bg-gray-700 text-white rounded-lg border border-gray-600" /&amp;gt;
        &amp;lt;input type="text" name="category" placeholder="Category" value={form.category} onChange={handleChange} required className="p-3 bg-gray-700 text-white rounded-lg border border-gray-600" /&amp;gt;
        &amp;lt;input type="number" name="price" placeholder="Price" value={form.price} onChange={handleChange} required className="p-3 bg-gray-700 text-white rounded-lg border border-gray-600" /&amp;gt;
        &amp;lt;input type="number" name="quantityInStock" placeholder="Stock Quantity" value={form.quantityInStock} onChange={handleChange} required className="p-3 bg-gray-700 text-white rounded-lg border border-gray-600" /&amp;gt;
        &amp;lt;div className="flex justify-between"&amp;gt;
          &amp;lt;button type="submit" className="bg-green-500 hover:bg-green-600 text-white py-2 px-4 rounded-lg"&amp;gt;{editingProduct ? "Update Product" : "Add Product"}&amp;lt;/button&amp;gt;
          &amp;lt;button type="button" onClick={() =&amp;gt; { setShowAddForm(false); setEditingProduct(null); }} className="bg-red-500 hover:bg-red-600 text-white py-2 px-4 rounded-lg"&amp;gt;Cancel&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/form&amp;gt;
    )}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Sell Product form
1.Allows selecting a product and entering the quantity to sell.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2.Fields:&lt;br&gt;
Dropdown: Selects a product from available ones.&lt;br&gt;
Quantity input: Specifies the number of units to sell.&lt;br&gt;
Submit button → Processes the sale and updates stock.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; {/* Sell Product Form */}
    {showSellForm &amp;amp;&amp;amp; (
      &amp;lt;form onSubmit={handleSellSubmit} className="bg-gray-800 p-6 rounded-xl shadow-lg grid gap-4 mt-4 w-full max-w-md mx-auto"&amp;gt;
        &amp;lt;h2 className="text-xl font-semibold text-white text-center"&amp;gt;Sell Product&amp;lt;/h2&amp;gt;
        &amp;lt;select name="productId" value={sellForm.productId} onChange={handleSellChange} required className="p-3 bg-gray-700 text-white rounded-lg border border-gray-600"&amp;gt;
          &amp;lt;option value=""&amp;gt;Select Product&amp;lt;/option&amp;gt;
          {products.map((product) =&amp;gt; (
            &amp;lt;option key={product._id} value={product._id}&amp;gt;{product.name} (Stock: {product.quantityInStock})&amp;lt;/option&amp;gt;
          ))}
        &amp;lt;/select&amp;gt;
        &amp;lt;input type="number" name="quantity" placeholder="Enter Quantity" value={sellForm.quantity} onChange={handleSellChange} required className="p-3 bg-gray-700 text-white rounded-lg border border-gray-600" /&amp;gt;
        &amp;lt;button type="submit" className="bg-yellow-500 hover:bg-yellow-600 text-white py-2 px-4 rounded-lg"&amp;gt;Sell Product&amp;lt;/button&amp;gt;
      &amp;lt;/form&amp;gt;
    )}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt; Product List Table&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;1.Displays all available products in a table.&lt;/p&gt;

&lt;p&gt;2.Columns:&lt;br&gt;
Product Name, Category, Price, Stock Quantity, Actions&lt;br&gt;
Edit button → Opens the edit form with pre-filled details.&lt;br&gt;
Delete button → Deletes the selected product.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{/* Product List */}
    &amp;lt;h3 className="text-xl font-bold mb-4 mt-6"&amp;gt;Product List&amp;lt;/h3&amp;gt;
    &amp;lt;div className="bg-gray-800 p-4 rounded-lg shadow-md"&amp;gt;
      &amp;lt;table className="w-full text-left"&amp;gt;
        &amp;lt;thead&amp;gt;
          &amp;lt;tr className="border-b border-gray-700 text-gray-300"&amp;gt;
            &amp;lt;th className="p-3"&amp;gt;Product&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Category&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Price&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Stock&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Actions&amp;lt;/th&amp;gt;
          &amp;lt;/tr&amp;gt;
        &amp;lt;/thead&amp;gt;
        &amp;lt;tbody&amp;gt;
          {products.map((product) =&amp;gt; (
            &amp;lt;tr key={product._id} className="border-b border-gray-700 text-gray-200"&amp;gt;
              &amp;lt;td className="p-3"&amp;gt;{product.name}&amp;lt;/td&amp;gt;
              &amp;lt;td&amp;gt;{product.category}&amp;lt;/td&amp;gt;
              &amp;lt;td&amp;gt;${product.price}&amp;lt;/td&amp;gt;
              &amp;lt;td&amp;gt;{product.quantityInStock}&amp;lt;/td&amp;gt;
              &amp;lt;td className="flex gap-2"&amp;gt;
                &amp;lt;button onClick={() =&amp;gt; handleEdit(product)} className="text-blue-400 hover:text-blue-600 p-2"&amp;gt;
                  &amp;lt;Edit3 size={20} /&amp;gt;
                &amp;lt;/button&amp;gt;
                &amp;lt;button onClick={() =&amp;gt; handleDelete(product._id)} className="text-red-500 hover:text-red-700 p-2"&amp;gt;
                  &amp;lt;Trash2 size={20} /&amp;gt;
                &amp;lt;/button&amp;gt;
              &amp;lt;/td&amp;gt;
            &amp;lt;/tr&amp;gt;
          ))}
        &amp;lt;/tbody&amp;gt;
      &amp;lt;/table&amp;gt;
    &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Stock Overview Component &lt;code&gt;components/StockOverview.jsx&lt;/code&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Importing Dependencies
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState } from "react"; //Manages state and API calls.
import { toast } from "react-toastify"; //Displays error messages if API calls fail.
import api from "../utils/api"; //Axios instance for API requests.
import { useNavigate } from "react-router-dom"; //Enables navigation between pages.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Component Initialization &amp;amp; State Management&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;1.stockData → Stores the stock details retrieved from the API.&lt;/p&gt;

&lt;p&gt;loading → Tracks whether data is still being fetched.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const navigate = useNavigate();
const [stockData, setStockData] = useState(null);
const [loading, setLoading] = useState(true);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Fetching the Stock Data
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
  fetchStockOverview();
}, []);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Fetching Stock Overview from API&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;1.Calls the API (/stock-overview) to retrieve stock details.&lt;/p&gt;

&lt;p&gt;2.Handles errors (logs error + displays a toast notification).&lt;/p&gt;

&lt;p&gt;3.Sets loading to false after fetching data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fetchStockOverview = async () =&amp;gt; {
  try {
    const { data } = await api.get("/stock-overview");
    setStockData(data);
  } catch (error) {
    console.error(error);
    toast.error("Failed to fetch stock overview");
  } finally {
    setLoading(false);
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;UI or Component Return Statement&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;1.Dashboard Navigation&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button 
  onClick={() =&amp;gt; navigate("/dashboard")} 
  className="flex items-center gap-2 bg-gray-600 hover:bg-gray-700 text-white py-2 px-4 rounded-lg shadow-md transition duration-300"
&amp;gt;
  &amp;lt;span&amp;gt;Back to Dashboard&amp;lt;/span&amp;gt;
&amp;lt;/button&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Stock Overview section
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h2 className="text-3xl font-bold text-gray-100 mb-6 text-center w-full"&amp;gt;
  Stock Overview
&amp;lt;/h2&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Stock Data Card
Displays 3 key metrics: Total Items, Total Sold, Total Revenue &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Skeleton Loading Effect: While fetching data, it displays a placeholder using animate-pulse.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div className="grid grid-cols-3 gap-6 text-center"&amp;gt;
  {loading ? (
    [...Array(3)].map((_, i) =&amp;gt; (
      &amp;lt;div key={i} className="p-6 bg-gray-800 rounded-lg shadow-md animate-pulse"&amp;gt;
        &amp;lt;div className="h-6 bg-gray-700 rounded w-3/4 mx-auto mb-2"&amp;gt;&amp;lt;/div&amp;gt;
        &amp;lt;div className="h-8 bg-gray-700 rounded w-1/2 mx-auto"&amp;gt;&amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    ))
  ) : (
    &amp;lt;&amp;gt;
      &amp;lt;div className="p-6 bg-gray-800 rounded-lg shadow-md"&amp;gt;
        &amp;lt;h3 className="text-lg font-semibold text-gray-300"&amp;gt;Total Items&amp;lt;/h3&amp;gt;
        &amp;lt;p className="text-2xl font-bold text-white"&amp;gt;{stockData.totalItems}&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div className="p-6 bg-gray-800 rounded-lg shadow-md"&amp;gt;
        &amp;lt;h3 className="text-lg font-semibold text-gray-300"&amp;gt;Total Sold&amp;lt;/h3&amp;gt;
        &amp;lt;p className="text-2xl font-bold text-white"&amp;gt;{stockData.totalSold}&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div className="p-6 bg-gray-800 rounded-lg shadow-md"&amp;gt;
        &amp;lt;h3 className="text-lg font-semibold text-gray-300"&amp;gt;Total Revenue&amp;lt;/h3&amp;gt;
        &amp;lt;p className="text-2xl font-bold text-green-400"&amp;gt;
          ${stockData.totalRevenue.toFixed(2)}
        &amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  )}
&amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Sold Items List&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Displays sold items in a list.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Shows a skeleton loading effect if data is still being fetched.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Handles empty data gracefully (No items sold yet.)&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div className="mt-8 bg-gray-800 p-6 rounded-lg shadow-md"&amp;gt;
  &amp;lt;h3 className="text-xl font-bold text-gray-100 mb-4"&amp;gt;Sold Items&amp;lt;/h3&amp;gt;
  &amp;lt;ul className="divide-y divide-gray-700"&amp;gt;
    {loading ? (
      [...Array(5)].map((_, i) =&amp;gt; (
        &amp;lt;li key={i} className="p-4 flex justify-between animate-pulse"&amp;gt;
          &amp;lt;div className="h-4 bg-gray-700 rounded w-1/3"&amp;gt;&amp;lt;/div&amp;gt;
          &amp;lt;div className="h-4 bg-gray-700 rounded w-1/4"&amp;gt;&amp;lt;/div&amp;gt;
          &amp;lt;div className="h-4 bg-gray-700 rounded w-1/6"&amp;gt;&amp;lt;/div&amp;gt;
          &amp;lt;div className="h-4 bg-gray-700 rounded w-1/6"&amp;gt;&amp;lt;/div&amp;gt;
        &amp;lt;/li&amp;gt;
      ))
    ) : stockData.soldItems.length &amp;gt; 0 ? (
      stockData.soldItems.map((item, index) =&amp;gt; (
        &amp;lt;li key={index} className="p-4 flex justify-between"&amp;gt;
          &amp;lt;span className="font-semibold text-white"&amp;gt;{item.name}&amp;lt;/span&amp;gt; 
          &amp;lt;span className="text-gray-400"&amp;gt;{item.category}&amp;lt;/span&amp;gt;
          &amp;lt;span className="text-green-500"&amp;gt;Sold: {item.quantitySold}&amp;lt;/span&amp;gt;
          &amp;lt;span className="text-blue-400"&amp;gt;
            Revenue: ${item.revenueGenerated.toFixed(2)}
          &amp;lt;/span&amp;gt;
        &amp;lt;/li&amp;gt;
      ))
    ) : (
      &amp;lt;p className="text-gray-500 text-center"&amp;gt;No items sold yet.&amp;lt;/p&amp;gt;
    )}
  &amp;lt;/ul&amp;gt;
&amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Analytics Component &lt;code&gt;components/Analytics.jsx&lt;/code&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Imports and Initial Setup.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState } from "react";
import { Bar } from "react-chartjs-2";  //Registers bar chart components.
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import api from "../utils/api"; // Using baseURL configured API
import { useNavigate } from "react-router-dom";

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;State Management
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [stockData, setStockData] = useState([]); //Stores fetched product stock data
const [chartData, setChartData] = useState(null); // Stores formatted data for Chart.js
const [category, setCategory] = useState(""); //Stores user-input filter for product category
const [sortBy, setSortBy] = useState("totalRevenue"); //Stores sorting criteria (totalRevenue or totalSold)
const [order, setOrder] = useState("desc"); //Determines sort order (asc or desc)
const [loading, setLoading] = useState(true); //Tracks data fetching state
const [error, setError] = useState(null); //Stores error messages

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Data fetching with UseEffect
Calls fetchStockData and fetchChartData whenever category, sortBy, or order changes.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
  fetchStockData();
  fetchChartData();
}, [category, sortBy, order]);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Fetching Stock Data
1.Sends API request to /analytics/stock to get stock details.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2.Filters products based on category (case-insensitive).&lt;/p&gt;

&lt;p&gt;3.Updates stockData with filtered results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fetchStockData = async () =&amp;gt; {
  setLoading(true);
  try {
    const response = await api.get(`/analytics/stock`, {
      params: { sortBy, order },
    });

    let filteredData = response.data;

    // Apply case-insensitive filtering on the frontend
    if (category.trim() !== "") {
      const searchQuery = category.toLowerCase();
      filteredData = filteredData.filter(product =&amp;gt;
        product.category.toLowerCase().includes(searchQuery) ||
        product.name.toLowerCase().includes(searchQuery)
      );
    }

    setStockData(filteredData);
  } catch (error) {
    setError("Error fetching stock data");
    console.error("Error fetching stock data:", error);
  } finally {
    setLoading(false);
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Fetching Chart Data&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;1.Calls API /analytics/chart-data to get total revenue &amp;amp; total sold per category.&lt;/p&gt;

&lt;p&gt;2.Converts response into chartData for Chart.js bar graph.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fetchChartData = async () =&amp;gt; {
  try {
    const response = await api.get(`/analytics/chart-data`);
    const data = response.data;
    setChartData({
      labels: data.map((item) =&amp;gt; item.category),
      datasets: [
        {
          label: "Total Revenue",
          data: data.map((item) =&amp;gt; item.totalRevenue || 0),
          backgroundColor: "rgba(54, 162, 235, 0.6)",
        },
        {
          label: "Total Sold",
          data: data.map((item) =&amp;gt; item.totalSold || 0),
          backgroundColor: "rgba(255, 99, 132, 0.6)",
        },
      ],
    });
  } catch (error) {
    setError("Error fetching chart data");
    console.error("Error fetching chart data:", error);
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;UI Rendering&lt;/li&gt;
&lt;li&gt;Navigation Button
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button 
  onClick={() =&amp;gt; navigate("/dashboard")} 
  className="flex items-center gap-2 bg-gray-600 hover:bg-gray-700 text-white py-2 px-4 rounded-lg shadow-md transition duration-300"
&amp;gt;
  &amp;lt;span&amp;gt;Back to Dashboard&amp;lt;/span&amp;gt;
&amp;lt;/button&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Filters and Sorting Options&lt;/li&gt;
&lt;li&gt;Text Input: Filters by category.&lt;/li&gt;
&lt;li&gt;Dropdowns:
1.Sort by (totalRevenue / totalSold).
2.Sort order (asc / desc).
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div className="flex gap-4 mb-4"&amp;gt;
  &amp;lt;input
    type="text"
    placeholder="Filter by category"
    value={category}
    onChange={(e) =&amp;gt; setCategory(e.target.value)}
    className="p-2 bg-gray-800 border border-gray-600 rounded"
  /&amp;gt;
  &amp;lt;select
    value={sortBy}
    onChange={(e) =&amp;gt; setSortBy(e.target.value)}
    className="p-2 bg-gray-800 border border-gray-600 rounded"
  &amp;gt;
    &amp;lt;option value="totalRevenue"&amp;gt;Sort by Revenue&amp;lt;/option&amp;gt;
    &amp;lt;option value="totalSold"&amp;gt;Sort by Items Sold&amp;lt;/option&amp;gt;
  &amp;lt;/select&amp;gt;
  &amp;lt;select
    value={order}
    onChange={(e) =&amp;gt; setOrder(e.target.value)}
    className="p-2 bg-gray-800 border border-gray-600 rounded"
  &amp;gt;
    &amp;lt;option value="desc"&amp;gt;Descending&amp;lt;/option&amp;gt;
    &amp;lt;option value="asc"&amp;gt;Ascending&amp;lt;/option&amp;gt;
  &amp;lt;/select&amp;gt;
&amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Table for Stock Data&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Displays product, category, sales count, and revenue.&lt;/p&gt;

&lt;p&gt;Uses stockData to generate rows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;table className="w-full border-collapse border border-gray-700"&amp;gt;
  &amp;lt;thead&amp;gt;
    &amp;lt;tr className="bg-gray-800"&amp;gt;
      &amp;lt;th className="p-2 border border-gray-700"&amp;gt;Product&amp;lt;/th&amp;gt;
      &amp;lt;th className="p-2 border border-gray-700"&amp;gt;Category&amp;lt;/th&amp;gt;
      &amp;lt;th className="p-2 border border-gray-700"&amp;gt;Items Sold&amp;lt;/th&amp;gt;
      &amp;lt;th className="p-2 border border-gray-700"&amp;gt;Revenue&amp;lt;/th&amp;gt;
    &amp;lt;/tr&amp;gt;
  &amp;lt;/thead&amp;gt;
  &amp;lt;tbody&amp;gt;
    {stockData.map((product) =&amp;gt; (
      &amp;lt;tr key={product._id} className="text-center bg-gray-700"&amp;gt;
        &amp;lt;td className="p-2 border border-gray-600"&amp;gt;{product.name}&amp;lt;/td&amp;gt;
        &amp;lt;td className="p-2 border border-gray-600"&amp;gt;{product.category}&amp;lt;/td&amp;gt;
        &amp;lt;td className="p-2 border border-gray-600"&amp;gt;{product.itemsSold}&amp;lt;/td&amp;gt;
        &amp;lt;td className="p-2 border border-gray-600"&amp;gt;
          ${product.totalRevenue ? product.totalRevenue.toFixed(2) : "0.00"}
        &amp;lt;/td&amp;gt;
      &amp;lt;/tr&amp;gt;
    ))}
  &amp;lt;/tbody&amp;gt;
&amp;lt;/table&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Chart.js Bar Chart&lt;/li&gt;
&lt;li&gt;If chartData exists, renders bar chart.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{chartData &amp;amp;&amp;amp; (
  &amp;lt;div className="mt-6 bg-gray-800 p-4 rounded-lg"&amp;gt;
    &amp;lt;h2 className="text-xl font-bold"&amp;gt;Sales &amp;amp; Revenue Overview&amp;lt;/h2&amp;gt;
    &amp;lt;Bar data={chartData} /&amp;gt;
  &amp;lt;/div&amp;gt;
)}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Landing Page &lt;code&gt;pages/LandingPage.jsx&lt;/code&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Handling imports
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useNavigate } from "react-router-dom";
import { ShoppingCart, BarChart3, FileText, LogIn } from "lucide-react";
import { AuthContext } from "../context/AuthContext";
import { useContext, useState } from "react";

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Component definition and AuthChecks&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;1.Extracts user and logout from AuthContext to manage authentication.&lt;/p&gt;

&lt;p&gt;2.isOpen controls the profile dropdown visibility.&lt;/p&gt;

&lt;p&gt;3.isAuthenticated checks if the user is logged in using localStorage token.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const LandingPage = () =&amp;gt; {
  const { user, logout } = useContext(AuthContext);
  const [isOpen, setIsOpen] = useState(false);
  const navigate = useNavigate();

  const handleLogout = () =&amp;gt; {
    logout();
    navigate("/");
    setIsOpen(false);
  };

  const isAuthenticated = !!localStorage.getItem("token");

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Handling Profile Click
Toggles the profile dropdown when clicked.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleProfileClick = async () =&amp;gt; {
  if (!isOpen) {
    await user;
  }
  setIsOpen(!isOpen);
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt; Handling Navigation
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleNavigation = (path) =&amp;gt; {
  navigate(isAuthenticated ? path : "/login");
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Landing page layout // Dark mode styling.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
  &amp;lt;div className="min-h-screen bg-gray-900 text-white flex flex-col items-center justify-center px-6 relative"&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Navbar section
1.If the user is logged in, show a profile button.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2.Clicking Profile reveals a dropdown with name, email, and a logout button.&lt;/p&gt;

&lt;p&gt;3.If not logged in, show Login &amp;amp; Register buttons.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{user ? (
  &amp;lt;div className="absolute top-6 right-6"&amp;gt;
    &amp;lt;button onClick={handleProfileClick} className="px-4 py-2 bg-gray-700 bg-opacity-70 hover:bg-opacity-100 rounded-md transition"&amp;gt;
      Profile
    &amp;lt;/button&amp;gt;

    {isOpen &amp;amp;&amp;amp; (
      &amp;lt;div className="absolute right-0 mt-2 w-56 bg-black text-gray-800 rounded-lg shadow-lg border border-white/20 transition-all duration-300"&amp;gt;
        &amp;lt;div className="p-4 border-b border-white/20"&amp;gt;
          &amp;lt;p className="font-semibold text-white"&amp;gt;{user.name}&amp;lt;/p&amp;gt;
          &amp;lt;p className="text-sm text-gray-300"&amp;gt;{user.email}&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;button onClick={handleLogout} className="block w-full text-left px-4 py-2 text-white hover:bg-white/20 rounded-b-lg transition"&amp;gt;
          Logout
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    )}
  &amp;lt;/div&amp;gt;
) : (
  &amp;lt;div className="absolute top-6 right-6 flex gap-4"&amp;gt;
    &amp;lt;button onClick={() =&amp;gt; navigate("/login")} className="text-white hover:text-blue-400 transition duration-300"&amp;gt;Login&amp;lt;/button&amp;gt;
    &amp;lt;span className="text-gray-500"&amp;gt;|&amp;lt;/span&amp;gt;
    &amp;lt;button onClick={() =&amp;gt; navigate("/auth/register")} className="text-white hover:text-green-400 transition duration-300"&amp;gt;Register&amp;lt;/button&amp;gt;
  &amp;lt;/div&amp;gt;
)}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Hero Section
Title &amp;amp; Description for the landing page.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;header className="text-center max-w-3xl"&amp;gt;
  &amp;lt;h1 className="text-4xl font-bold mb-4"&amp;gt;Stock Management System&amp;lt;/h1&amp;gt;
  &amp;lt;p className="text-gray-300"&amp;gt;
    A powerful tool to track inventory, manage stock levels, and generate reports efficiently.
  &amp;lt;/p&amp;gt;
&amp;lt;/header&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Features Section&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;1.Displays 3 feature cards (Product Management, Stock Overview, Analysis).&lt;/p&gt;

&lt;p&gt;2.If user is not authenticated, an extra card for Secure Login appears.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;section className="mt-12 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8 text-center"&amp;gt;
  {[
    {
      path: "/products",
      icon: &amp;lt;ShoppingCart size={40} className="text-yellow-400 mx-auto mb-3" /&amp;gt;,
      title: "Product Management",
      description: "Easily add, edit, and delete products in stock.",
    },
    {
      path: "/stock-overview",
      icon: &amp;lt;BarChart3 size={40} className="text-green-400 mx-auto mb-3" /&amp;gt;,
      title: "Stock Overview",
      description: "Monitor available stock, items sold, and revenue trends.",
    },
    {
      path: "/analytics",
      icon: &amp;lt;FileText size={40} className="text-purple-400 mx-auto mb-3" /&amp;gt;,
      title: "Analysis",
      description: "Generate reports in charts.",
    },
  ].map((feature, index) =&amp;gt; (
    &amp;lt;div key={index} onClick={() =&amp;gt; handleNavigation(feature.path)}
      className="bg-gray-800 p-6 rounded-lg shadow-md cursor-pointer hover:bg-gray-700 transition duration-300"&amp;gt;
      {feature.icon}
      &amp;lt;h3 className="text-xl font-semibold"&amp;gt;{feature.title}&amp;lt;/h3&amp;gt;
      &amp;lt;p className="text-gray-400 mt-2"&amp;gt;{feature.description}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  ))}

  {!isAuthenticated &amp;amp;&amp;amp; (
    &amp;lt;div onClick={() =&amp;gt; navigate("/login")}
      className="bg-gray-800 p-6 rounded-lg shadow-md cursor-pointer hover:bg-gray-700 transition duration-300"&amp;gt;
      &amp;lt;LogIn size={40} className="text-red-400 mx-auto mb-3" /&amp;gt;
      &amp;lt;h3 className="text-xl font-semibold"&amp;gt;Secure Login&amp;lt;/h3&amp;gt;
      &amp;lt;p className="text-gray-400 mt-2"&amp;gt;Ensure security with JWT-based authentication.&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  )}
&amp;lt;/section&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Footer Section.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;footer className="mt-12 text-gray-500 text-center"&amp;gt;
  &amp;amp;copy; {new Date().getFullYear()} Stock Management System By Shaik Reshma
&amp;lt;/footer&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Checkout my project source code 👉&lt;a href="https://github.com/Shaikr786/Stock-Management-System" rel="noopener noreferrer"&gt;github&lt;/a&gt; and the you'll find the deployed link, Test it out there.&lt;/p&gt;

&lt;p&gt;This is all about frontend setup code and run the application npm run dev.For any queries react out in comment section.&lt;/p&gt;

&lt;h1&gt;
  
  
  Happy Developing🎉
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                       Let's grow together!
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw58nvux1017sjq3ydf51.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw58nvux1017sjq3ydf51.png" alt="tq" width="562" height="594"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Frontened Setup🛠 - Stock Management System</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Sun, 06 Apr 2025 09:52:38 +0000</pubDate>
      <link>https://dev.to/shaikr786/common-errors-in-frontened-setup-stock-management-system-2f1e</link>
      <guid>https://dev.to/shaikr786/common-errors-in-frontened-setup-stock-management-system-2f1e</guid>
      <description>&lt;p&gt;As we are done with our 👉&lt;a href="https://dev.to/shaikr786/stock-management-system-backend-deployment-cag"&gt;Backend&lt;/a&gt; to set up frontend for MERN Stack Application, Let's use &lt;a href="https://vite.dev/" rel="noopener noreferrer"&gt;Vite&lt;/a&gt; framework for building react application.&lt;/p&gt;

&lt;p&gt;So, Inorder to complete the steps of our Stock Management System we need to build the frontend that aligns the below requirements.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fls5l4xg4e8yejd4rgvcq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fls5l4xg4e8yejd4rgvcq.png" alt="Plan" width="723" height="775"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;1.In your Main Project Directory open terminal and follow the steps.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a Vite project
npm create vite@latest stock-management-frontend --template react

# Navigate to the project directory
cd stock-management-frontend

# Install dependencies
npm install

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2.Install required dependencies&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install react-router-dom  //React Router for navigation

npm install axios  //Axios for API requests

npm install react-toastify  //React-Toastify for notifications

npm install chart.js react-chartjs-2 //Chart.js for stock trend 
visualization

npm install file-saver //FileSaver for CSV export:

npm install jwt-decode  //To decode JWT tokens

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;p&gt;For Styling install &lt;a href="https://tailwindcss.com/docs/installation/using-vite" rel="noopener noreferrer"&gt;tailwindcss for Vite configuration.&lt;/a&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Set up Base API URL for Fetch Requests (api.js), Login page, Register page.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;utils/api.js&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import axios from "axios";

const BASE_URL = "http://localhost:5000/api"; // Change this for production

const api = axios.create({
  baseURL: BASE_URL,
  headers: {
    "Content-Type": "application/json",
  },
});

export default api;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;pages/Register.jsx&lt;/code&gt; - create a registration form as per our backend requriements.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Defining the register component.&lt;/li&gt;
&lt;li&gt;State Management of the fields.&lt;/li&gt;
&lt;li&gt;Handling the form Submission.&lt;/li&gt;
&lt;li&gt;Creating UserInterface as per your styling requirements.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from "react";
import { useNavigate } from "react-router-dom";
import api from "../utils/api"; // Import the centralized API instance

const Register = () =&amp;gt; {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [role, setRole] = useState("user");
  const navigate = useNavigate();

  const handleRegister = async (e) =&amp;gt; {
    e.preventDefault(); //prevents default form submission.
    try {
      await api.post("/auth/register", { name, email, password, role });
      navigate("/login");
    } catch (error) {
      alert(error.response?.data?.message || "Registration failed!");
    }
  };

  return (
    &amp;lt;div className="flex justify-center items-center h-screen bg-gray-200"&amp;gt;
      &amp;lt;form onSubmit={handleRegister} className="bg-white p-6 rounded shadow-lg"&amp;gt;
        &amp;lt;h2 className="text-2xl mb-4"&amp;gt;Register&amp;lt;/h2&amp;gt;
        &amp;lt;input 
          type="text" placeholder="Name" 
          className="mb-2 p-2 w-full border" 
          value={name} 
          onChange={(e) =&amp;gt; setName(e.target.value)} 
        /&amp;gt;
        &amp;lt;input 
          type="email" placeholder="Email" 
          className="mb-2 p-2 w-full border" 
          value={email} 
          onChange={(e) =&amp;gt; setEmail(e.target.value)} 
        /&amp;gt;
        &amp;lt;input 
          type="password" placeholder="Password" 
          className="mb-2 p-2 w-full border" 
          value={password} 
          onChange={(e) =&amp;gt; setPassword(e.target.value)} 
        /&amp;gt;
        &amp;lt;select 
          className="mb-2 p-2 w-full border" 
          value={role} 
          onChange={(e) =&amp;gt; setRole(e.target.value)}
        &amp;gt;
          &amp;lt;option value="user"&amp;gt;User&amp;lt;/option&amp;gt;
          &amp;lt;option value="admin"&amp;gt;Admin&amp;lt;/option&amp;gt;
        &amp;lt;/select&amp;gt;
        &amp;lt;button type="submit" className="w-full bg-green-500 text-white p-2"&amp;gt;
          Register
        &amp;lt;/button&amp;gt;
      &amp;lt;/form&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Register;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;pages/Login.jsx&lt;/code&gt;  - Create a Login form as per our backend requriements.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;State Management of required fields.&lt;/li&gt;
&lt;li&gt;Accessing the Login Function from AuthContext&lt;/li&gt;
&lt;li&gt;Navigation After Successful Login&lt;/li&gt;
&lt;li&gt;Handling the Login submission&lt;/li&gt;
&lt;li&gt;User Interface
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { AuthContext } from "../context/AuthContext";

const Login = () =&amp;gt; {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const { login } = useContext(AuthContext);
  const navigate = useNavigate();

  const handleLogin = async (e) =&amp;gt; {
    e.preventDefault();
    try {
      await login(email, password);
      navigate("/dashboard");
    } catch (error) {
      alert(error.message);
    }
  };

  return (
    &amp;lt;div className="flex justify-center items-center h-screen bg-gray-200"&amp;gt;
      &amp;lt;form onSubmit={handleLogin} className="bg-white p-6 rounded shadow-lg"&amp;gt;
        &amp;lt;h2 className="text-2xl mb-4"&amp;gt;Login&amp;lt;/h2&amp;gt;
        &amp;lt;input
          type="email"
          placeholder="Email"
          className="mb-2 p-2 w-full border"
          value={email}
          onChange={(e) =&amp;gt; setEmail(e.target.value)}
        /&amp;gt;
        &amp;lt;input
          type="password"
          placeholder="Password"
          className="mb-2 p-2 w-full border"
          value={password}
          onChange={(e) =&amp;gt; setPassword(e.target.value)}
        /&amp;gt;
        &amp;lt;button type="submit" className="w-full bg-blue-500 text-white p-2"&amp;gt;Login&amp;lt;/button&amp;gt;
      &amp;lt;/form&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Login;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;5.Setup Authentication in frontend using AuthCotext.&lt;/p&gt;

&lt;p&gt;The common issues I faced everytime like,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Login persists only on the first login, but logs out on page refresh.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Private routes might not be handling the user state correctly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The dashboard appears empty after login due to a delay in fetching user data.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Token might not be set correctly before fetching user data.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;🔧 Fixed Code&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;AuthProvider (Fix User Persistence on Refresh)&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Importing Required Dependencies&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Creating the Authentication Context&lt;br&gt;
-Creates AuthContext, allowing components to access authentication data without prop drilling.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Defining the AuthProvider Component&lt;br&gt;
-This component wraps the entire application, providing authentication state to all components.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Defining the State Variables&lt;br&gt;
-user: Stores authenticated user details.&lt;br&gt;
-token: Stores the authentication token, initially retrieved from localStorage if available.&lt;br&gt;
-loading: Indicates whether authentication actions are in progress (useful for UI handling).&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;5.Handling Token Changes &amp;amp; User Authentication (useEffect)&lt;br&gt;
  -Runs whenever token changes.&lt;br&gt;
  -If a valid token exists, it:&lt;br&gt;
     Sets the token in Axios headers for all requests.&lt;br&gt;
     Calls fetchUser() to get user details.&lt;br&gt;
     If no token exists, it:&lt;br&gt;
  -Removes the Authorization header.&lt;br&gt;
  -Logs the user out by setting user to null.&lt;br&gt;
  -Stops loading.&lt;/p&gt;

&lt;p&gt;6.Fetching User Details (fetchUser)&lt;/p&gt;

&lt;p&gt;7.Handling Login (login function)&lt;/p&gt;

&lt;p&gt;8.Handling Logout (logout function)&lt;/p&gt;

&lt;p&gt;9.Providing Authentication Context to Components&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createContext, useState, useEffect } from "react";
import api from "../utils/api";

export const AuthContext = createContext();

const AuthProvider = ({ children }) =&amp;gt; {
  const [user, setUser] = useState(null);
  const [token, setToken] = useState(localStorage.getItem("token") || "");
  const [loading, setLoading] = useState(true);

  useEffect(() =&amp;gt; {
    console.log("Token in AuthProvider:", token);

    if (token) {
      api.defaults.headers.common["Authorization"] = `Bearer ${token}`;
      fetchUser();
    } else {
      delete api.defaults.headers.common["Authorization"];
      setUser(null);
      setLoading(false);
    }
  }, [token]);

  const fetchUser = async () =&amp;gt; {
    try {
      const token = localStorage.getItem("token");
      if (!token) {
        console.error("No token found, logging out...");
        logout();
        return;
      }

      console.log("Fetching user with token:", token);
      const { data } = await api.get("/auth/me", {
        headers: { Authorization: `Bearer ${token}` },
      });

      console.log("User fetched successfully:", data);
      setUser(data);
    } catch (error) {
      console.error("Failed to fetch user:", error.response?.data || error.message);
      logout();
    } finally {
      setLoading(false); // ✅ Ensures loading stops
    }
  };

  const login = async (email, password) =&amp;gt; {
    try {
      const { data } = await api.post("/auth/login", { email, password });
      setToken(data.token);
      setUser(data.user);
      localStorage.setItem("token", data.token);
      api.defaults.headers.common["Authorization"] = `Bearer ${data.token}`;
    } catch (error) {
      throw new Error(error.response?.data?.message || "Login failed");
    }
  };

  const logout = () =&amp;gt; {
    setToken("");
    setUser(null);
    localStorage.removeItem("token");
    delete api.defaults.headers.common["Authorization"];
    setLoading(false); // ✅ Stop loading after logout
  };

  return (
    &amp;lt;AuthContext.Provider value={{ user, token, login, logout, loading }}&amp;gt;
      {children}
    &amp;lt;/AuthContext.Provider&amp;gt;
  );
};

export default AuthProvider;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;PrivateRoute (Prevent Redirect on Refresh Before Auth Check) - used to protect routes that require authentication.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Navigate } from "react-router-dom";
import { useContext } from "react";
import { AuthContext } from "../context/AuthContext";

const PrivateRoute = ({ children }) =&amp;gt; { //Represents the protected component/page.
  const { user, loading } = useContext(AuthContext);

  if (loading) return &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;; // Prevents navigation issues

  return user ? {children} : &amp;lt;Navigate to="/login" /&amp;gt;;
};

export default PrivateRoute;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Dashboard (Fix Logout Handling)
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useContext } from "react";
import { AuthContext } from "../context/AuthContext";

const Dashboard = () =&amp;gt; {
  const { user } = useContext(AuthContext);

  if (!user) {
    return &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;;
  }

  return (
    &amp;lt;div&amp;gt;
        &amp;lt;h1 className="text-2xl font-bold mb-4"&amp;gt;Dashboard&amp;lt;/h1&amp;gt;
      &amp;lt;h1&amp;gt;Welcome, {user.name}&amp;lt;/h1&amp;gt;
      &amp;lt;p&amp;gt;Email: {user.email}&amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;Role: {user.role}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Dashboard;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;App.jsx&lt;/code&gt; - Update the main component for setting the frontend routes for navigation.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import AuthProvider from "./context/AuthContext";
import Login from "./pages/Login";
import Dashboard from "./pages/Dashboard";
import PrivateRoute from "./routes/PrivateRoute";
import Register from "./pages/Register";

const App = () =&amp;gt; {
  return (
    &amp;lt;AuthProvider&amp;gt;
      &amp;lt;Router&amp;gt;
        &amp;lt;Routes&amp;gt;
          &amp;lt;Route path="/login" element={&amp;lt;Login /&amp;gt;} /&amp;gt;
          &amp;lt;Route path="/auth/register" element={&amp;lt;Register /&amp;gt;} /&amp;gt;
          &amp;lt;Route element={&amp;lt;PrivateRoute /&amp;gt;}&amp;gt;
            &amp;lt;Route path="/dashboard" element={&amp;lt;Dashboard /&amp;gt;} /&amp;gt; 
          &amp;lt;/Route&amp;gt;
        &amp;lt;/Routes&amp;gt;
      &amp;lt;/Router&amp;gt;
    &amp;lt;/AuthProvider&amp;gt;
  );
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, after login the result page of the dashboard will be up like,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fskz42mpknzydbd0n2b8k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fskz42mpknzydbd0n2b8k.png" alt="output" width="800" height="377"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hurray!🎉 We are done with auth based and private route based setup in frontend which is 50% completion of our application.&lt;/p&gt;

&lt;p&gt;Let's continue further in upcoming blog post.Reach out in comment section for any queires.&lt;/p&gt;

&lt;p&gt;Happy developing!&lt;/p&gt;

&lt;blockquote&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                      Let's grow together
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsuitawrqgzdzcn46ixkl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsuitawrqgzdzcn46ixkl.png" alt="upvote" width="562" height="594"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Stock Management System - Backend Deployment</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Sat, 05 Apr 2025 00:03:12 +0000</pubDate>
      <link>https://dev.to/shaikr786/stock-management-system-backend-deployment-cag</link>
      <guid>https://dev.to/shaikr786/stock-management-system-backend-deployment-cag</guid>
      <description>&lt;p&gt;Hii Guys!&lt;/p&gt;

&lt;p&gt;Let's build the additional features that completes the setup as per our task requirements in continution to 👉&lt;a href="https://dev.to/shaikr786/stock-management-system-backend-setup-1i1g"&gt;Backend Setup&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxdfde4e8iffpub10gjb1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxdfde4e8iffpub10gjb1.png" alt="Plan" width="612" height="768"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Step by step implementation of additional steps.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;1. CSV Import/Export for Stock Details&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Allowing admin to upload CSV File to add/update the products.&lt;/li&gt;
&lt;li&gt;Providing an endpoint to download the current stock data as csv&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;inorder to perform these steps, create a model and perform actions according to the get and post routes for csv file to store data into the database rather than storageMemory.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;CSVFile.js&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require("mongoose");

const csvFileSchema = new mongoose.Schema({
    filename: String,
    mimetype: String,
    data: Buffer, // Store the CSV file as binary
    uploadedAt: { type: Date, default: Date.now }
});

module.exports = mongoose.model("CSVFile", csvFileSchema);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;create a middleware for csv file in &lt;code&gt;authMiddleware.js&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multer = require("multer");

const storage = multer.memoryStorage(); // Store file in memory as Buffer
const upload = multer({ storage });

module.exports = {upload};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Define route in the &lt;code&gt;server.js&lt;/code&gt; inorder to perform the creation of routes and controller actions.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;csvRoutes.js&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const { importCSV, exportCSV } = require("../controllers/csvController");
const {upload} = require("../middleware/authMiddleware");

const router = express.Router();

router.post("/import-csv", upload.single("file"), importCSV);
router.get("/export-csv", exportCSV);

module.exports = router;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;code&gt;csvController.js&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Logic for importing the csv file and storing results in Products file.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const importCSV = async (req, res) =&amp;gt; {
    try {
        if (!req.file) {
            return res.status(400).json({ error: "No file uploaded!" });
        }

        // Convert buffer data to stream
        const csvStream = Readable.from(req.file.buffer.toString());

        let products = [];
        csvStream
            .pipe(csv.parse({ headers: true }))
            .on("data", (row) =&amp;gt; {
                products.push({
                    name: row["Product Name"], // Mapping CSV column to schema field
                    category: row["Category"],
                    price: parseFloat(row["Price"]), // Ensure numeric value
                    stockQuantity: parseInt(row["Stock Quantity"]), // Ensure integer
                    itemsSold: parseInt(row["Items Sold"]) // Ensure integer
                });
            })
            .on("end", async () =&amp;gt; {
                try {
                    await Product.insertMany(products);
                    res.status(200).json({ message: "CSV imported successfully and stored in DB!" });
                } catch (err) {
                    console.error("Error inserting data:", err);
                    res.status(500).json({ error: "Error inserting data" });
                }
            });

    } catch (error) {
        console.error("CSV Import Error:", error);
        res.status(500).json({ error: "Error importing CSV" });
    }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Logic for the exporting the products data in the form of csv file.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const exportCSV = async (req, res) =&amp;gt; {
    try {
        // Find the most recent CSV file from the database
        const latestFile = await CSVFile.findOne().sort({ uploadedAt: -1 });

        if (!latestFile) {
            return res.status(404).json({ error: "No CSV file found" });
        }

        res.setHeader("Content-Type", latestFile.mimetype);
        res.setHeader("Content-Disposition", `attachment; filename=${latestFile.filename}`);
        res.send(latestFile.data);
    } catch (error) {
        res.status(500).json({ error: "Error exporting CSV" });
    }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and export the functions inorder to get referenced to the routes, to perform action with respect to the route.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Filters and Sorting on Stock Overview&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Implementing query parameters for filtering and sorting stock data.&lt;/li&gt;
&lt;li&gt;Define the routes for the analytics in &lt;code&gt;server.js&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use("/api/analytics", analyticsRoutes);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;analyticsRoutes.js&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const { getStockData, getChartData } = require('../controllers/analyticsController');

const router = express.Router();
router.get('/stock', getStockData); //Fetching stock with filters.

router.get('/chart-data', getChartData);//fetching the data for presenting in chart.


module.exports = router;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Then complete the controller functions to complete the actions to their respective routes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;by requiring the Products model, to the &lt;code&gt;analyticsController.js&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;functions, 
1.Filters Products by Category
If a category query parameter is provided (e.g., &lt;code&gt;/stock?category=Fruits)&lt;/code&gt;, it filters products based on that category.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;2.Sorts Products Based on Query Parameters&lt;br&gt;
 If sortBy is provided (e.g., &lt;code&gt;/stock?sortBy=price)&lt;/code&gt;, it sorts the results:&lt;br&gt;
    Ascending (asc or default) → order=1&lt;br&gt;
    Descending (desc) → order=-1&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/stock?sortBy=price&amp;amp;order=desc → Sorts by price in descending order
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3.Finds and Returns Sorted &amp;amp; Filtered Data&lt;br&gt;
  Applies filtering (filter) if category is provided.&lt;/p&gt;

&lt;p&gt;Applies sorting (sortOptions) if sortBy and order are given.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getStockData = async (req, res) =&amp;gt; {
    try {
        let { category, sortBy, order } = req.query;
        let filter = {};
        let sortOptions = {};

        if (category) filter.category = category;
        if (sortBy) sortOptions[sortBy] = order === "desc" ? -1 : 1;

        const products = await Product.find(filter).sort(sortOptions);
        res.status(200).json(products);
    } catch (error) {
        res.status(500).json({ message: "Error fetching stock data", error });
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Display Charts for Stock Trends and Revenue&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;analyticsController.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const getChartData = async (req, res) =&amp;gt; {
    try {
        const products = await Product.find();

        const categories = {};
        products.forEach(product =&amp;gt; {
            if (!categories[product.category]) {
                categories[product.category] = { totalRevenue: 0, totalSold: 0 };
            }
            categories[product.category].totalRevenue += product.totalRevenue;
            categories[product.category].totalSold += product.itemsSold;
        });

        const chartData = Object.keys(categories).map(category =&amp;gt; ({
            category,
            totalRevenue: categories[category].totalRevenue,
            totalSold: categories[category].totalSold
        }));

        res.status(200).json(chartData);
    } catch (error) {
        res.status(500).json({ message: "Error fetching chart data", error });
    }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Test your backend api&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I have tested everyting in &lt;a href="https://youtu.be/KlL5-m6Lr4Y" rel="noopener noreferrer"&gt;here&lt;/a&gt; just visit the link for testing the api.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Deployment Of Backend API&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Create a repository Stock-Management-Api.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Push the code to this repo.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;verify my repo to get the code.&lt;a href="https://github.com/Shaikr786/Stock-Management-Api" rel="noopener noreferrer"&gt;GithubLink&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;create vercel.json file in root directory inorder to handle the deployment in vercel.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "version": 2,
    "builds": [
      {
        "src": "server.js",
        "use": "@vercel/node"
      }
    ],
    "routes": [
      {
        "src": "/(.*)",
        "dest": "server.js"
      }
    ]
  }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;go to &lt;a href="https://vercel.com/" rel="noopener noreferrer"&gt;vercel.com&lt;/a&gt; create an account and add a new project for deployment.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnbgtkvxt9ggt8ke4ta7e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnbgtkvxt9ggt8ke4ta7e.png" alt="Image description" width="313" height="414"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Select your repo and import it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjje3d64xzs129tb8r56d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjje3d64xzs129tb8r56d.png" alt="Image description" width="753" height="322"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Provide the environment variables and path to root directory.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F36ojbslyugpjb1au2jho.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F36ojbslyugpjb1au2jho.png" alt="Image description" width="800" height="608"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Then click on deploy.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpj62txvii8ot18evbi1x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpj62txvii8ot18evbi1x.png" alt="Image description" width="800" height="238"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Congratulations! U just deployed your backend API.&lt;/p&gt;

&lt;h1&gt;
  
  
  Happy Developing.
&lt;/h1&gt;

&lt;p&gt;Let's continue frontend part in upcoming blogs.For any queries reach out in comment section.&lt;/p&gt;

&lt;p&gt;Thank You!&lt;/p&gt;

&lt;blockquote&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                       Let's grow together!
&lt;/code&gt;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Firmoik4zyy6qn5dnafhg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Firmoik4zyy6qn5dnafhg.png" alt="Image description" width="562" height="594"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>beginners</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Stock Management System- Backend Setup</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Thu, 03 Apr 2025 17:12:00 +0000</pubDate>
      <link>https://dev.to/shaikr786/stock-management-system-backend-setup-1i1g</link>
      <guid>https://dev.to/shaikr786/stock-management-system-backend-setup-1i1g</guid>
      <description>&lt;p&gt;Hii Guys!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This blog is the continution to 👉&lt;a href="https://dev.to/shaikr786/stock-management-system-2ilh"&gt;Stock Management System&lt;/a&gt; ,Please go through the process&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As we set up the basic API end points.Let's move forward to complete the requirements.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxdfde4e8iffpub10gjb1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxdfde4e8iffpub10gjb1.png" alt="Plan" width="612" height="768"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Completing the Products Module with all required CURD operations performance in productController&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;productController.js&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Adding a new Product - destructuring the field names to its requested json body, and adding them to the product object then storing them to the database asper the Model defined.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const addProduct = async (req, res) =&amp;gt; {
    try {
        const { name, category, price, stockQuantity } = req.body;
        const product = new Product({ name, category, price, stockQuantity, itemsSold: 0 });
        await product.save();
        res.status(201).json({ message: 'Product added successfully', product });
    } catch (error) {
        res.status(500).json({ message: 'Error adding product', error });
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Fetch all products - find() method applied to the particular model, to fetch all existing products.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const getProducts = async (req, res) =&amp;gt; {
    try {
        const products = await Product.find();
        res.status(200).json(products);
    } catch (error) {
        res.status(500).json({ message: 'Error fetching products', error });
    }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Update a product - Based on productId retrieving data and modifying the json and then saving the results.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const updateProduct = async (req, res) =&amp;gt; {
    try {
        const { id } = req.params;
        const updatedProduct = await Product.findByIdAndUpdate(id, req.body, { new: true });
        if (!updatedProduct) {
            return res.status(404).json({ message: 'Product not found' });
        }
        res.status(200).json({ message: 'Product updated successfully', updatedProduct });
    } catch (error) {
        res.status(500).json({ message: 'Error updating product', error });
    }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Delete a Product - by fetching productId and performing action.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const deleteProduct = async (req, res) =&amp;gt; {
    try {
        const { id } = req.params;
        const deletedProduct = await Product.findByIdAndDelete(id);
        if (!deletedProduct) {
            return res.status(404).json({ message: 'Product not found' });
        }
        res.status(200).json({ message: 'Product deleted successfully' });
    } catch (error) {
        res.status(500).json({ message: 'Error deleting product', error });
    }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally export the arrow functions to import in respective routes referenced.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;productRoutes.js&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const { getProducts, addProduct, updateProduct, deleteProduct } = require('../controllers/productController');
const router = express.Router();

router.post('/products', addProduct);
router.get('/products', getProducts);
router.put('/products/:id', updateProduct);
router.delete('/products/:id', deleteProduct);

module.exports = router;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Test these curd operations like we did previously to get these restful API's working correct.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Implementing the Business Logic.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;Business Logic - The rules and operations that define how data should be processed according to the business needs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So, as per our needs we are implementing the business logic under 4conditions satisfying to manage the stock.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Updating the stock when sale happens.&lt;/li&gt;
&lt;li&gt;Preventing sales if stock is insufficient.&lt;/li&gt;
&lt;li&gt;Calculating total revenue based on sales.&lt;/li&gt;
&lt;li&gt;Sending alerts when stock is low.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;-&amp;gt; So, to implement above steps.Create a new &lt;code&gt;sales.js&lt;/code&gt; route.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const { sellProduct } = require("../controllers/productController");

const router = express.Router();
// Endpoint to handle sales
router.post("/sell", sellProduct);
module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-&amp;gt; Now Update the controller function to perform the actions in particular route.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// Sell Product and Update Stock
const sellProduct = async (req, res) =&amp;gt; {
    try {
        const { productId, quantity } = req.body; // Get product ID and quantity from request

        // Check if product exists
        const product = await Product.findById(productId);
        if (!product) {
            return res.status(404).json({ message: "Product not found" });
        }

        // Prevent sales if stock is insufficient
        if (product.quantityInStock &amp;lt; quantity) {
            return res.status(400).json({ message: "Insufficient stock available" });
        }

        // Update stock and sales details
        product.quantityInStock -= quantity; // Reduce stock
        product.itemsSold += quantity; // Increase total items sold
        product.totalRevenue += quantity * product.price; // Calculate revenue

        // Save updated product details
        await product.save();

        // Check if stock is low and send an alert (For example, if stock &amp;lt; 5)
        if (product.quantityInStock &amp;lt; 5) {
            console.log(`⚠️ Alert: Stock for ${product.name} is low! Only ${product.quantityInStock} left.`);
            // You can also trigger an email or notification system here
        }

        res.status(200).json({
            message: "Sale successful",
            updatedProduct: product
        });
    } catch (error) {
        res.status(500).json({ message: "Server Error", error: error.message });
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-&amp;gt; Now to get stock overview, create &lt;code&gt;stock.js&lt;/code&gt; route and handle the controller function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const { stockOverview } = require("../controllers/stockController");

const router = express.Router();
// Get stock overview (total items sold and revenue)
router.get("/", stockOverview);

module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;stockController.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Product = require('../models/Product');

const stockOverview = async (req, res) =&amp;gt; {
    try {
        console.log("Stock overview API called"); // Check if API is called

        const products = await Product.find(); // Fetch all products

        let totalItems = 0;
        let totalSold = 0;
        let totalRevenue = 0;
        let soldItems = [];

        products.forEach(product =&amp;gt; {
            totalItems += product.quantityInStock || 0;
            totalSold += product.itemsSold || 0;
            totalRevenue += product.totalRevenue || 0;

            if (product.itemsSold &amp;amp;&amp;amp; product.itemsSold &amp;gt; 0) { // Ensure condition is met
                soldItems.push({
                    name: product.name,
                    category: product.category,
                    quantitySold: product.itemsSold,
                    revenueGenerated: product.totalRevenue
                });
            }
        });

        res.status(200).json({
            totalItems,
            totalSold,
            totalRevenue,
            soldItems
        });
    } catch (error) {
        console.error("Stock Overview Error:", error.message);
        res.status(500).json({ message: "Server Error", error: error.message });
    }
};


module.exports = {
    stockOverview
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-&amp;gt; Test this api endpoint to get the required results.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foaz84nx64glp51036hoj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foaz84nx64glp51036hoj.png" alt="Image description" width="800" height="312"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Now that we are done with business logic let's complete our bonus steps.i.e, Authentication, CSV Uploads,  filters and sorting on stock overview, Charts for visualizing stock trends and revenue.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;3.User Authentication.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Setup User Model &lt;code&gt;models/User.js&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;1.A MongoDB NoSql schema for data storage and retrieval.Provide all the required fields in the schema so that user model can perform all functionalities.&lt;br&gt;
  2.Password Hashing to protect the user credentials in the database.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const UserSchema = new mongoose.Schema({
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    role: { type: String, enum: ["admin", "user"], default: "user" }
});

// Hash password before saving
UserSchema.pre("save", async function (next) {
    if (!this.isModified("password")) return next();
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
});

module.exports = mongoose.model("User", UserSchema);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;User Registration API &lt;code&gt;controllers/authController.js&lt;/code&gt; - a controller function that provides all the fields wrt the user model so as to save the registered details, as per the request sent by the user.A duplicate user check is done before registering and storing to the database.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const User = require("../models/User");

const registerUser = async (req, res) =&amp;gt; {
    try {
        const { name, email, password, role } = req.body;

        let user = await User.findOne({ email });
        if (user) return res.status(400).json({ message: "User already exists" });

        user = new User({ name, email, password, role });
        await user.save();

        res.status(201).json({ message: "User registered successfully" });
    } catch (error) {
        res.status(500).json({ message: "Server Error", error: error.message });
    }
};

module.exports = { registerUser };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;User Login &amp;amp; JWT Token &lt;code&gt;controllers/authController.js&lt;/code&gt; - User Authentication is done by using &lt;a href="https://www.npmjs.com/package/jsonwebtoken" rel="noopener noreferrer"&gt;jsonwebtokens&lt;/a&gt;.
1.As per the requested login credentials which are destructured and then email is checked in the database whether it exists or not,if not the response is returned with the status code 500.
2.If user exists ,then password check is done as the password is hashed in the databased it is retrieved to its normal form and compared with the user requested password using &lt;a href="https://www.npmjs.com/package/bcrypt" rel="noopener noreferrer"&gt;bcrypt&lt;/a&gt; if no match we get error with status.
3.If there is a match a token is generated from the sign method of jwt.The secret key is used to sign the token to ensure its authenticity, is defined in &lt;code&gt;.env&lt;/code&gt; file.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/User");

const loginUser = async (req, res) =&amp;gt; {
    try {
        const { email, password } = req.body;

        const user = await User.findOne({ email });
        if (!user) return res.status(400).json({ message: "Invalid email or password" });

        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) return res.status(400).json({ message: "Invalid email or password" });

        const token = jwt.sign({ id: user._id, role: user.role }, process.env.JWT_SECRET, { expiresIn: "1d" });

        res.json({ token, user: { id: user._id, name: user.name, email: user.email, role: user.role } });
    } catch (error) {
        res.status(500).json({ message: "Server Error", error: error.message });
    }
};

module.exports = { registerUser, loginUser };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;add these routes to &lt;code&gt;server.js&lt;/code&gt; and test the endpoints to ensure it's working is fine.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Protect Routes with Middleware &lt;code&gt;middleware/authMiddleware.js&lt;/code&gt; - To get the authorized access of the particular routes create  a middleware based on the token, to allow access after verifying it.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const jwt = require("jsonwebtoken");

const protect = (req, res, next) =&amp;gt; {
    const token = req.header("Authorization")?.split(" ")[1];

    if (!token) return res.status(401).json({ message: "Access Denied" });

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded;
        next();
    } catch (error) {
        res.status(403).json({ message: "Invalid Token" });
    }
};

module.exports = protect;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;use in Routes &lt;code&gt;routes/stockRoutes.js&lt;/code&gt; - add the middleware in the routes where you want to perform authorized access.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;router.get("/stock-overview", protect, stockOverview);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Role Based Access Control&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;1.modify &lt;code&gt;authMiddleware.js&lt;/code&gt; - create a middleware to specify the Role based access to seperate the user centric functionality.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const adminOnly = (req, res, next) =&amp;gt; {
    if (req.user.role !== "admin") {
        return res.status(403).json({ message: "Access denied. Admins only" });
    }
    next();
};

module.exports = { protect, adminOnly };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Use in Admin Routes - here for creating new product admins only has the access, if user tries to access it then access denied message is generated.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { protect, adminOnly } = require("../middleware/authMiddleware");

router.post("/add-product", protect, adminOnly, addProduct);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Connect routes in &lt;code&gt;routes/userRoutes.js&lt;/code&gt; - update the routes ,by providing the respective functionality.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const { registerUser, loginUser } = require("../controllers/authController");

const router = express.Router();

router.post("/register", registerUser);
router.post("/login", loginUser);

module.exports = router;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and call this authRoutes in &lt;code&gt;server.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const userRoutes = require('./routes/userRoutes');
app.use("/api/auth", userRoutes);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;test these endpoints to ensure they are working fine.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;As the jsonwebtokens provides the authorized access to the routes through middleware which is passed inside the routes that specifies only registered or logged in user is allowed to access the particular route controllers.&lt;/li&gt;
&lt;li&gt;When it comes to role based access I have specified the role in User model so that if the logged in user is admin he has his own functionality and that is be differed with user access, which is even specified in the authMiddleware.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's complete the further steps in upcoming blog. Reach out in comment section for any queries.&lt;br&gt;
Happy Developing!&lt;/p&gt;

&lt;blockquote&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                       Let'grow together            
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnnm4ujujoqlg0eoi2ctl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnnm4ujujoqlg0eoi2ctl.png" alt="Image description" width="562" height="594"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>beginners</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Stock Management System - Basic Setup</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Thu, 03 Apr 2025 13:09:00 +0000</pubDate>
      <link>https://dev.to/shaikr786/stock-management-system-2ilh</link>
      <guid>https://dev.to/shaikr786/stock-management-system-2ilh</guid>
      <description>&lt;p&gt;Hi Guys!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Let's Build a MERN Stack Application from scratch,A Stock Management System as part of this plan let's complete this step by step.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxdfde4e8iffpub10gjb1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxdfde4e8iffpub10gjb1.png" alt="Plan" width="612" height="768"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Backend Setup
&lt;/h2&gt;

&lt;p&gt;1.Initialize the project directory and split the folder by creating subfolders as client and server.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;And now we complete the server setup.&lt;br&gt;
code along with me in IDE called VSCode.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir stock-management-system &amp;amp;&amp;amp; cd stock-management-system
mkdir backend &amp;amp;&amp;amp; cd backend
npm init -y

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2.After initializing the package.json install the backend dependencies that are required to build our project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express mongoose dotenv cors jsonwebtoken bcryptjs multer nodemon

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3.Maintain a directory structure in this format to address the code with no trouble and to maintain a clear view.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;backend/
│── models/
│   ├── Product.js
│   ├── User.js
│── routes/
│   ├── productRoutes.js
│   ├── userRoutes.js
│── controllers/
│   ├── productController.js
│   ├── userController.js
│── middleware/
│   ├── authMiddleware.js
│── config/
│   ├── db.js
│── uploads/
│── .env
│── server.js
│── package.json

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;4.Start coding &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Connect database
&lt;strong&gt;db.js&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require('mongoose');
const connectDB = async () =&amp;gt; {
    try {
        const conn = await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log(`MongoDB Connected: ${conn.connection.host}`);
    } catch (error) {
        console.error(`Error: ${error.message}`);
        process.exit(1);
    }
};
module.exports = connectDB;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;create model&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Product.js&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
    name: { type: String, required: true },
    category: { type: String, required: true },
    price: { type: Number, required: true },
    stockQuantity: { type: Number, required: true },
    itemsSold: { type: Number, default: 0 },
    description: { type: String }
}, { timestamps: true });

module.exports = mongoose.model('Product', productSchema);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;provide routes to specified model&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;productRoute.js&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const { getProducts, createProduct } = require('../controllers/productController');
const router = express.Router();

router.get('/', getProducts);
router.post('/', createProduct);

module.exports = router;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;perform controller functions to perform actions on routes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;productController.js&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Product = require('../models/Product');

exports.getProducts = async (req, res) =&amp;gt; {
    const products = await Product.find({});
    res.json(products);
};

exports.createProduct = async (req, res) =&amp;gt; {
    const { name, category, price, stockQuantity, description } = req.body;
    const product = new Product({ name, category, price, stockQuantity, description });
    await product.save();
    res.status(201).json(product);
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;set up the server
&lt;strong&gt;server.js&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const dotenv = require('dotenv');
const cors = require('cors');
const connectDB = require('./config/db');
const productRoutes = require('./routes/productRoutes');

dotenv.config();
connectDB();

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

app.use('/api/products', productRoutes);

app.listen(5000, () =&amp;gt; console.log('Server running on port 5000'));

app.get('/', (req, res) =&amp;gt; {
    res.send('API is running...');
}   );  

module.exports = app;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Start the Server&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;code&gt;npm start&lt;/code&gt; -&amp;gt; as you need to specify under the scripts inside the &lt;code&gt;package.json&lt;/code&gt; file as&lt;br&gt;
&lt;code&gt;"start": "nodemon server.js"&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmeu823eiemrvn95prznq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmeu823eiemrvn95prznq.png" alt="Image description" width="800" height="332"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you Got to see the above result your server is live at port 5000.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Test the API&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;now U are all set to test the api created to implement the basic product specific model and product specific actions inorder to execute and test it using the api testing tools like Thunder Client or the Postman based on your preferences.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;I'm using Thunder client which is a VSCode extension, just install and proceed to continue along.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;1.Provide a get request &lt;code&gt;http://localhost:5000/&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fivp9t31qft4cucup64vn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fivp9t31qft4cucup64vn.png" alt="Image description" width="800" height="127"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;2.Add a product based on model specified using post request.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiavebkhzj2qa02zzgayx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiavebkhzj2qa02zzgayx.png" alt="Image description" width="800" height="334"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;3.Test the another route we have created, to get all the products.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzvu0rfg83ghh3sn43i4d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzvu0rfg83ghh3sn43i4d.png" alt="Image description" width="800" height="490"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Explanation&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;In API Testing of the CURD operations plays a crutial role which are defined in routes i.e. Controllers&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;to post a product, the server is requesting a json body that is aligned with the model specified fields to be matched, as the  client sends the response as described in image 2.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    const { name, category, price, stockQuantity, description } = req.body;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;2.The response is printed with status code specified by the user.&lt;br&gt;
&lt;code&gt;res.status(200).json(products);&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
3.And the get request of getting all the products with find query&lt;br&gt;
&lt;code&gt;const products = await Product.find({});&lt;/code&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;For any errors U can even get the results in console log to know what is breaking, or U can use the middleware directly to address the errors&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use((err, req, res, next) =&amp;gt; {
    const statusCode = res.statusCode ? res.statusCode : 500;
    res.status(statusCode);
    res.json({
        message: err.message,
        stack: process.env.NODE_ENV === 'production' ? null : err.stack,
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Don't forget to setup the environment variables, &lt;code&gt;.env&lt;/code&gt; file&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Hurray!😃 we have completed our basic backned setup!&lt;/p&gt;

&lt;p&gt;Let's continue in further in upcoming blog.&lt;/p&gt;

&lt;p&gt;Happy Developing!&lt;/p&gt;

&lt;blockquote&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                     Let's grow together!
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9irf22azkoqfufvmivxz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9irf22azkoqfufvmivxz.png" alt="Image description" width="562" height="594"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>MERN Stack Deployment Issue🛠</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Sat, 22 Mar 2025 18:14:50 +0000</pubDate>
      <link>https://dev.to/shaikr786/mern-stack-deployment-issue-4h21</link>
      <guid>https://dev.to/shaikr786/mern-stack-deployment-issue-4h21</guid>
      <description>&lt;p&gt;To resolve this issue! 🤔&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1yb1jju3odzd8lq2h5za.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1yb1jju3odzd8lq2h5za.png" alt="Image description" width="800" height="537"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It has a simple Solution Go to MongoDB in your Project Find Network Access in security tab ,&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Add IP Address&lt;br&gt;
Allow Access From Anywhere&lt;br&gt;
Confirm&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The other possible issues might be &lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Incorrect vercel configuration.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Missing or Incorrect Environment Variables&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Memory or Execution Time Limit Exceeded&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;If still didn't found debug the issue by &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;1.Check Vercel Logs&lt;/p&gt;

&lt;p&gt;Run: vercel logs &lt;/p&gt;

&lt;p&gt;Or go to the Vercel Dashboard &amp;gt; Project &amp;gt; Functions &amp;gt; Logs to see detailed errors.&lt;/p&gt;

&lt;p&gt;2.Test Locally&lt;/p&gt;

&lt;p&gt;Run: vercel dev to test the function before deploying.&lt;/p&gt;

&lt;p&gt;3.Redeploy Your Project&lt;/p&gt;

&lt;p&gt;Run: vercel --prod to force a fresh deployment.&lt;/p&gt;

&lt;p&gt;React if you like it helpful.😊&lt;br&gt;
Happy Developing!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>beginners</category>
      <category>opensource</category>
    </item>
    <item>
      <title>create-react-app❌</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Fri, 07 Mar 2025 09:46:13 +0000</pubDate>
      <link>https://dev.to/shaikr786/create-react-app-k9h</link>
      <guid>https://dev.to/shaikr786/create-react-app-k9h</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As, we all know about the update of the deprecation of create-react-app ,and the &lt;a href="https://react.dev/blog/2025/02/14/sunsetting-create-react-app" rel="noopener noreferrer"&gt;&lt;strong&gt;documentation&lt;/strong&gt;&lt;/a&gt; itself suggests to go with other popular apps or frameworks!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  So, what are your preferences right now? And why do you choose?
&lt;/h2&gt;

&lt;p&gt;Let's listen to people in Comments&lt;br&gt;
Happy developing!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpm5y0y28r7ojlygr0u98.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpm5y0y28r7ojlygr0u98.jpeg" alt="Image description" width="204" height="192"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>React - MERN Stack</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Tue, 04 Mar 2025 17:56:41 +0000</pubDate>
      <link>https://dev.to/shaikr786/react-mern-stack-5fef</link>
      <guid>https://dev.to/shaikr786/react-mern-stack-5fef</guid>
      <description>&lt;p&gt;Let's learn and develop along.!😊&lt;/p&gt;

&lt;h6&gt;
  
  
  Part5
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;If anyone missed the previous part you can vist from here 
&lt;a href="https://dev.to/shaikr786/user-authentication-jsonwebtokens-mern-stack-1ipk"&gt;checkout&lt;/a&gt;👈&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Today let's understand React from Mern Stack, it's importance in the MERN Stack project.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is React?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As we know react is a Javascript library which mostly helpful to create UI's for websites, apps etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why React?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As we all know Javascript is the core language which is the foundation for libraries and other frameworks like React.&lt;br&gt;
If we look at the pros and cons of the Javascript&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl5wvs2qm1u8pwe26kv2w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl5wvs2qm1u8pwe26kv2w.png" alt="Image description" width="300" height="168"&gt;&lt;/a&gt;&lt;br&gt;
Pros:&lt;/p&gt;

&lt;p&gt;1.In the beginning Javascript has large popularity due it's fast responsive behaviour, Versatile nature, simple &amp;amp; lightweight, user friendly, browser supportive, etc.&lt;/p&gt;

&lt;p&gt;2.It Works fine for small and medium projects with simple DOM manipulations.&lt;/p&gt;

&lt;p&gt;Cons: &lt;/p&gt;

&lt;p&gt;1.Hard for DOM manipulation of large and complex projects.&lt;/p&gt;

&lt;p&gt;2.unorganized behaviour of code.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;So, react is helpful for: &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq02w1ltcto4ac3e413ug.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq02w1ltcto4ac3e413ug.png" alt="Image description" width="300" height="168"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Component based architechture for better code organization and structuring.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Creates a Virtual DOM(Document Object Model) with respect to the actual DOM for handling efficient and fast rendering ,results in better performance.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Due to it's component structure the code is Reusable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;React is best for creating Single Page Application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;React also offers ecosystem of tools like Redux, Node, Flux. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Also React has several Disadvantages which was solved further using Next.Js which is on top of React ,and is on top of Javascript.&lt;/p&gt;

&lt;p&gt;So,as we got a glimpse of the working of React Let's start over working with the project.&lt;/p&gt;

&lt;h2&gt;
  
  
  React Project - MERN Stack.
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;As we set up the backend and performed the user auth in previous sections.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Now we are creating a new folder in the main directory called client,as react handles all client side information.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2t1zlp0zxmhpgjefvp8q.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2t1zlp0zxmhpgjefvp8q.jpg" alt="Image description" width="388" height="433"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;press &lt;code&gt;ctrl+&lt;/code&gt;&lt;code&gt;and in the client directory and create react app in the current directory&lt;/code&gt;npx create-react-app@latest .` as '.' denotes current directory.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk9z9hcligvy6zbz8sfxn.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk9z9hcligvy6zbz8sfxn.jpg" alt="Image description" width="800" height="538"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we get the deprecating warning which tells,&lt;/p&gt;

&lt;p&gt;1.Create React App (CRA) is no longer actively maintained.&lt;/p&gt;

&lt;p&gt;2.React recommends using Next.js, Remix, or Vite for new projects.&lt;/p&gt;

&lt;p&gt;3.go through the link as it provides clear blog post from ur installation, for better understanding about the deprecation.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Despite this, the installation continued.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8072t732pdsdqfktg45e.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8072t732pdsdqfktg45e.jpg" alt="Image description" width="800" height="477"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It provides the scripts to start the react app.So,follow the instruction and run &lt;code&gt;npm start&lt;/code&gt; to start the react app locally.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flsy00whrmv9ch0ibcc5j.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flsy00whrmv9ch0ibcc5j.jpg" alt="Image description" width="800" height="469"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can see the directory structure of the client with installed nodemodules, scripts and all required dependencies used by react to create the app.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fewd7susyokzsitj6y76x.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fewd7susyokzsitj6y76x.jpg" alt="Image description" width="800" height="501"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is how we start working with react.If u want my content as out for faster delivery.Let's develop together.&lt;/p&gt;

&lt;p&gt;Happy Developing!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvtva2q3irayq4jitlr2m.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvtva2q3irayq4jitlr2m.jpeg" alt="Image description" width="204" height="192"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>beginners</category>
      <category>javascript</category>
      <category>react</category>
    </item>
    <item>
      <title>Virtual Environment for Projects🤔- Python</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Tue, 04 Mar 2025 08:50:29 +0000</pubDate>
      <link>https://dev.to/shaikr786/virtual-environment-for-projects-python-2lhc</link>
      <guid>https://dev.to/shaikr786/virtual-environment-for-projects-python-2lhc</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;When setting up any project of any technology setting up virtual environment is not necessary.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But for working with python projects I got to know that Setting Up a Virtual Environment is must and necessary step.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why a Virtual Environment?&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;It is a containarized isolated enviroment which helps to maintain all the files related to this project like python files, packages, dependencies, installations, configurations etc. and provides a better organization so that, it doesn't interfear in other system settings and other projects.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;1.Dependency Management – Each project can have its own isolated dependencies, preventing conflicts between different versions of packages.&lt;br&gt;
   2.Avoid System-Level Changes – Installing packages globally can mess up system dependencies or cause issues with other projects.&lt;br&gt;
   3.Reproducibility – You can share requirements.txt or pyproject.toml to recreate the exact environment on another machine.&lt;br&gt;
   4.Better Organization – Keeps project-specific packages separate, reducing clutter in the global Python environment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When You might not need one?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When you are working on smaller scripts or a one time task then u might not need it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;How to set up Virtual Environment for Python Projects?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;I'm working on a flask project,so to setup the virtual env&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;1.Go to that folder open with VSCode (IDE of your choice).&lt;br&gt;
 2.press  &lt;code&gt;ctrl+&lt;/code&gt;`  to open the terminal.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Now run the command &lt;code&gt;pip install virtualenv&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvnyhj15nh5f0qavkntss.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvnyhj15nh5f0qavkntss.jpg" alt="img" width="800" height="387"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To create a virtual environment run  &lt;code&gt;virtualenv env&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;or run the command  &lt;code&gt;python -m venv venv&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;then activate it run  &lt;code&gt;venv\Scripts\activate&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftp0ilw4rbtbarqzvwiuw.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftp0ilw4rbtbarqzvwiuw.jpg" alt="py" width="800" height="67"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;You can see(venv) is set before the path,which specifies virtual environment is set to your directory.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Then install your required dependencies which you want to work with.&lt;br&gt;
&lt;code&gt;&lt;/code&gt;&lt;code&gt;&lt;br&gt;
pip install -r requirements.txt&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It is simple but effectively important.Do,not miss this step if did then face the complications.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Reach out for any content you are looking for and help me improve my developing skills.let's learn and innovate together.Please do react and make me understand my content was satisfactory.😊&lt;/p&gt;

&lt;p&gt;Happy developing!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm92vyr32yeakre1i5qy7.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm92vyr32yeakre1i5qy7.jpeg" alt="Image description" width="204" height="192"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>basic</category>
    </item>
    <item>
      <title>Python Version Setup</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Tue, 04 Mar 2025 06:57:23 +0000</pubDate>
      <link>https://dev.to/shaikr786/python-version-setup-3bo2</link>
      <guid>https://dev.to/shaikr786/python-version-setup-3bo2</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;To see the updated python version in commandline after installing the latest version of python from &lt;a href="https://www.python.org/" rel="noopener noreferrer"&gt;official website&lt;/a&gt;, after setting up into your system.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;1.Open the commandline or powershell to check for the updated version, and type &lt;code&gt;python --version&lt;/code&gt;&lt;br&gt;
2.if you see the latest version as a result then you are good to go.&lt;br&gt;
3.But, if u see the result as previous version even after installing the latest version successfully like- &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;if u have previously 3.10 version and u want to update to latest like 3.13 and ur set up was done successfully by installing to ur system.&lt;/li&gt;
&lt;li&gt;and when u verify the version ur getting same previous one which should not.&lt;/li&gt;
&lt;li&gt;we will fix this by positioning the path from evironment variables.
4.Open environment variables to check whether it is added to the path or not &lt;/li&gt;
&lt;li&gt;&lt;p&gt;Press &lt;code&gt;windows+R&lt;/code&gt; and type &lt;code&gt;sysdm.cpl&lt;/code&gt; and hit enter.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fghy2qy3gdqahpyeu11l4.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fghy2qy3gdqahpyeu11l4.jpg" alt="congif" width="570" height="337"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Go to advanced and Select Environment Variables&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzmta2rq9vquswn1w1imj.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzmta2rq9vquswn1w1imj.jpg" alt="open" width="607" height="705"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;then go to System Variables and select path and click on edit and see if the path was there or not &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fez18mhtph0ar3bvexzuy.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fez18mhtph0ar3bvexzuy.jpg" alt="env" width="800" height="457"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After selecting if u see there is a path see the position and select the python313 and its scripts, moveup to the top &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F30rnovainvm5ltk153ha.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F30rnovainvm5ltk153ha.jpg" alt="upq" width="754" height="813"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hit ok and Now exit the cmd and open again.&lt;br&gt;
Now check &lt;code&gt;python --version&lt;/code&gt; You will get the updated version &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx42r4luwrm8wrbkfsafa.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx42r4luwrm8wrbkfsafa.jpg" alt="result" width="453" height="70"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You are good to go Now.&lt;/p&gt;

&lt;p&gt;Happy Developing!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0xppi3fjxvapk16k58kn.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0xppi3fjxvapk16k58kn.jpeg" alt="tq" width="204" height="192"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>python</category>
      <category>beginners</category>
      <category>basic</category>
    </item>
    <item>
      <title>The journey-Confused❌Organized✔️</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Sat, 01 Mar 2025 18:21:06 +0000</pubDate>
      <link>https://dev.to/shaikr786/the-journey-confusedorganized-3enp</link>
      <guid>https://dev.to/shaikr786/the-journey-confusedorganized-3enp</guid>
      <description>&lt;p&gt;Hello World .!Before starting ,Let me ask you something..&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Are u confused in choosing your techstack or ur organized in ur path?comment down below😊Let's see how may want to know how to be organized.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Most of the 50% engineers are confused to select the role to select as their job like me.&lt;br&gt;
-It's not wrong ,eitherways they get most of the oppurtunities to select and move forward accordingly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;And it is organized when you are consistant in whatever tech stack you are following ,And surely connections are important to help you out interms of fixing things .&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;What works more is the &lt;strong&gt;time&lt;/strong&gt; and &lt;strong&gt;consistancy&lt;/strong&gt;, If you are perfect in this then you are good to go.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Don't skip things in trying something new whether it may leave you bugs all day .But what it leaves you is the knowledge behind solving those bugs easily for rest.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Y companies ask for the experience for freshers?? &lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Most of us react like ...without joining any company how can get any kind of experience.?🙄Right?Yeah, But this tells them ur unique behaviour and the intrest towards this field by putting u different from other applicants.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;So,Try! not hard but smarter.Smart enough to adapt things easily.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Now that if ur intrested let's go further!😁&lt;/strong&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;If you have started a particular course which involves multiple new stuff and if you pic one ,it has it's own story?for example:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Full Stack Development&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;As this is involved with various stack ultimately results in developing a production ready application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;if you pick java it has it's story ,and if it's js it's linked with different pillars like Node, React ,so on and so forth...&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;what u need to understand here is the main pillar.In my case &lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Javascript&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A scripting language which provides a dynamic view to the web applicaitions.And the frameworks ,libraries are built on it,to work with it's scalability, redundant application and performace factor.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Documentation is the 1st priority and based on that topic we see different experts try to help us understand its functioning so explore them as per ur needs.If you find the things are getting repeated again again,then think of it as important.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;What the pitfalls would be is you will fail in implementing it,or simply the app yells at you in your 1st build not once but may be many times.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;But think this no one can dislike you forever,so do an application?which is built by you ?No right!&lt;/p&gt;

&lt;p&gt;So if done ,you will get the satisfaction of you achieved something.And you will get a story to share amoung.Yes!This sounds crazy about developing.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Happy Developing!Just smile and startover.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0a9ewngd3aycvk44qmrj.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0a9ewngd3aycvk44qmrj.jpeg" alt="i" width="204" height="192"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>softwaredevelopment</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Connecting AI Agent with UI - State Management🧩</title>
      <dc:creator>Reshma Shaik</dc:creator>
      <pubDate>Fri, 28 Feb 2025 19:16:04 +0000</pubDate>
      <link>https://dev.to/shaikr786/connecting-ai-agent-with-ui-state-management-289j</link>
      <guid>https://dev.to/shaikr786/connecting-ai-agent-with-ui-state-management-289j</guid>
      <description>&lt;p&gt;&lt;strong&gt;Image Generation In Next.js application.&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;From your UI based on your prompt message the copilot agent going to generate the image in your desired location.🤨&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Thinking how? If so,let's dive in :)&lt;/p&gt;

&lt;p&gt;Hello World! 😀&lt;br&gt;
How are you all doing?Hoping everything is fine!😉So,Today let's dive in with my new stuff which i'm excited to share and if ur intrested u can try along.!👌&lt;br&gt;
As the title of my post describes about ** &lt;a href="https://www.oracle.com/in/artificial-intelligence/ai-agents/" rel="noopener noreferrer"&gt;AI Agent&lt;/a&gt; ** and &lt;a href="https://www.copilotkit.ai/" rel="noopener noreferrer"&gt;&lt;strong&gt;copilotkit&lt;/strong&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;What are these..?Suddenly Y I ended up connecting these things? Yes,I got the same question when I was doing,But this is fascinating experience where, letting ai agent connect with us and do stuff which we specify with my little document knowledge itself made me more intrested in diving more deeper.&lt;/p&gt;

&lt;p&gt;I love this evolution, where there is continues growth!Unlike getting stuck in building and recovering things from bugs and bugs and bugs..😓 through the entire day,which is literally a hopeless experience .And this exciting experience journey.I'm thankful to see such a drastic change in me aswell.Hahahhaa..its quite a story right? I know !😅&lt;/p&gt;

&lt;p&gt;In my view &lt;a href="https://github.com/CopilotKit/CopilotKit" rel="noopener noreferrer"&gt;&lt;strong&gt;CopilotKit&lt;/strong&gt;&lt;/a&gt; works more efficient and smooth  than tools like &lt;strong&gt;&lt;a href="https://github.com/assistant-ui/assistant-ui" rel="noopener noreferrer"&gt;assistant-ui&lt;/a&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;a href="https://github.com/langchain-ai/open-canvas" rel="noopener noreferrer"&gt;open-canvas&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;What we will walk through here is ,assuming that you are connected to to your nextjs applicaiton with copilot kit if not it's a simple step go through the &lt;a href="https://docs.copilotkit.ai/quickstart" rel="noopener noreferrer"&gt;documentation&lt;/a&gt; you will find the selfhosting part or copilot cloud, based on your preference go through it.And set things up like choosing amoung:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;CopilotPopup&lt;/li&gt;
&lt;li&gt;CopilotSidebar&lt;/li&gt;
&lt;li&gt;CopilotChat&lt;/li&gt;
&lt;li&gt;Headless UI
I'm working with CopilotkitSidebar.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Unsplash Account&lt;/strong&gt; - it's free&lt;br&gt;
Now to generate images based on your prompts, create an account in &lt;a href="https://unsplash.com/developers" rel="noopener noreferrer"&gt;unsplash&lt;/a&gt;, and create your new application and access api key token to fetch the images through url, which hepls to generate images based on the url encoding, which will be handled through the state management.&lt;/p&gt;
&lt;h2&gt;
  
  
  ConnectData.tsx
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Create a new component in your next.js application.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Here we use 2 hooks, useCopilotReadable(), useCopilotAction() from @copilotkit/react-core library.&lt;br&gt;&lt;br&gt;
&lt;strong&gt;&lt;a href="https://docs.copilotkit.ai/reference/hooks/useCopilotReadable" rel="noopener noreferrer"&gt;useCopilotReadable&lt;/a&gt;&lt;/strong&gt;&lt;br&gt;
This hook helps to read the state from the UI.&lt;br&gt;
Example:&lt;/p&gt;


&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useCopilotReadable({
    description: "User-provided prompt when Copilot cannot generate an image",
    value: imagePrompt,
  });
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;as the default library provides the hook with different parameters described.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4vys6j9hl1w5ce7zjgf4.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4vys6j9hl1w5ce7zjgf4.jpg" alt="Image description" width="800" height="425"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;&lt;a href="https://docs.copilotkit.ai/reference/hooks/useCopilotAction" rel="noopener noreferrer"&gt;useCopilotAction&lt;/a&gt;&lt;/strong&gt;&lt;br&gt;
This hook helps to write state to the UI.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ixp4u98hms464ybus84.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ixp4u98hms464ybus84.jpg" alt="Image description" width="800" height="394"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;define the component which you want to display&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;for example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function ConnectData() {

  return(
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;AI Image Generator&amp;lt;/h2&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;input
          type="text"
          placeholder="Describe an image..."/&amp;gt;
        &amp;lt;button&amp;gt;Save Prompt&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
     &amp;lt;div&amp;gt;
            &amp;lt;p&amp;gt;Prompt:&amp;lt;/p&amp;gt;
            &amp;lt;img src={} alt="Generated"/&amp;gt;
     &amp;lt;/div&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Now, to handle states from UI ,I declared 3 useState() hooks.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//for image output
 const [images, setImages] = useState&amp;lt;ImageObject[]&amp;gt;([]);
//for prompt input
  const [imagePrompt, setImagePrompt] = useState&amp;lt;string&amp;gt;("");
//for highlight input
  const [needsUserInput, setNeedsUserInput] = useState(false);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;update the UI state handlers and the display in the return component with preferred tailwindCSS.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
    &amp;lt;div className="p-6"&amp;gt;
      &amp;lt;h2 className="text-2xl font-semibold"&amp;gt;AI Image Generator&amp;lt;/h2&amp;gt;

      {/* ✅ Input box is ALWAYS visible, but highlights when needed */}
      &amp;lt;div
        className={`flex flex-col items-center bg-white p-6 rounded-lg shadow-lg w-96 border 
        ${needsUserInput ? "border-red-500 shadow-red-300" : "border-gray-300"}
        transition-all duration-300`}
      &amp;gt;
        &amp;lt;input
          type="text"
          placeholder="Describe an image..."
          value={imagePrompt}
          onChange={(e) =&amp;gt; setImagePrompt(e.target.value)}
          className={`w-full p-3 border rounded-md focus:outline-none text-gray-700 shadow-sm
          ${needsUserInput ? "border-red-500 focus:ring-2 focus:ring-red-500" : "border-gray-300 focus:ring-blue-500"}
          transition-all duration-300`}
        /&amp;gt;

        &amp;lt;button
          onClick={() =&amp;gt; setNeedsUserInput(false)}
          className="mt-4 px-6 py-2 bg-blue-600 text-white font-semibold rounded-md shadow-md hover:bg-blue-700 transition-all duration-200"
        &amp;gt;
          Save Prompt
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;

      {/* ✅ Display generated images */}
      &amp;lt;div className="mt-5 flex flex-wrap gap-4"&amp;gt;
        {images.map((img) =&amp;gt; (
          &amp;lt;div key={img.id} className="border p-3 rounded-lg shadow-md"&amp;gt;
            &amp;lt;p className="font-semibold"&amp;gt;Prompt: {img.prompt}&amp;lt;/p&amp;gt;
            &amp;lt;img src={img.url} alt="Generated" className="w-48 rounded-md" /&amp;gt;
          &amp;lt;/div&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;reading input from the ui by copilotkit
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  // ✅ Log state changes when CopilotKit requires input
  useCopilotReadable({
    description: "User-provided prompt when Copilot cannot generate an image",
    value: imagePrompt,
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;fetching images from the unsplash
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; // ✅ Function to fetch an image based on the user's prompt
  const fetchImageByPrompt = async (prompt: string): Promise&amp;lt;ImageObject | null&amp;gt; =&amp;gt; {
    try {
      const response = await fetch(`https://source.unsplash.com/featured/?${encodeURIComponent(prompt)}`);
      return { id: crypto.randomUUID(), url: response.url, prompt };
    } catch (error: unknown) {
        if(error)
        {
            console.log(error);
        }else{
            console.log("unknown error occured");
        }

      return null;
    }
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;returning user specific output
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ✅ Copilot Action: Generates image, keeps input field intact
  useCopilotAction({
    name: "generateImage",
    description: "Generate an image based on a user's description",
    parameters: [],
    handler: async () =&amp;gt; {
      if (!imagePrompt.trim()) {
        setNeedsUserInput(true);
        console.log("CopilotKit: Needs user input for prompt.");
        return "I need a description to generate an image. Please enter one.";
      }

      const newImage = await fetchImageByPrompt(imagePrompt);

      if (!newImage) {
        setNeedsUserInput(true);
        console.log("CopilotKit: Image generation failed, requesting new input.");
        return "I couldn't generate an image. Please provide a new prompt.";
      }

      setNeedsUserInput(false);
      setImagePrompt(""); // Reset the prompt after successful generation
      setImages((prevImages) =&amp;gt; [...prevImages, newImage]);
      console.log("CopilotKit: Image generated successfully.");
      return `Generated an image for: "${imagePrompt}"`;
    },
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;from the above steps if you add this component to your main page it looks like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzsbclw17x740grq9djvz.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzsbclw17x740grq9djvz.jpg" alt="Image description" width="800" height="365"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;And if you check your console log and you can test it's state management , starting from reading input ,fetching images, generating results everything can be kept track.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If not attempted the prompt and asked copilotkit to generate image it triggers the ui component in highlight state, which uses &lt;br&gt;
our boolean highlight input hook.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftmu389wlrpnquzgn6ed5.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftmu389wlrpnquzgn6ed5.jpg" alt="Image description" width="800" height="347"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If entered proper prompt, the state is updated when we click on the save prompt that triggers the copilotAction to respond to the prompt when user types generate image in the chat,which results in creating the result in our specified location.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F43rw9cos39i0bxdg12o7.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F43rw9cos39i0bxdg12o7.jpg" alt="Image description" width="800" height="364"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;U can either check the console.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa05c1eqhkg0fr05jy4ru.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa05c1eqhkg0fr05jy4ru.jpg" alt="Image description" width="800" height="437"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Doesn't this interaction  with AI Agent represents Developer mode UI-Agent Interaction.😄I did enjoyed writing this.What about you.Share your expreriences, queries or anything else in comment section.&lt;br&gt;
I'd love to reach out.&lt;br&gt;
Happy developing.Bye bye!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa6fd2ssq75lpoc7ltzss.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa6fd2ssq75lpoc7ltzss.jpeg" alt="TQ" width="204" height="192"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>webdev</category>
      <category>nextjs</category>
      <category>agentaichallenge</category>
    </item>
  </channel>
</rss>
