0% found this document useful (0 votes)
11 views3 pages

Supermarket Billing System Code

The document contains a React component for a supermarket billing system, which allows users to input product details and generate a bill. It includes functionality to fetch product information from a backend API, validate input fields, and display a table of added products. The component also handles the submission of bill data to the backend for processing.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Supermarket Billing System Code

The document contains a React component for a supermarket billing system, which allows users to input product details and generate a bill. It includes functionality to fetch product information from a backend API, validate input fields, and display a table of added products. The component also handles the submission of bill data to the backend for processing.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

cd "C:\Users\RAZZ\Downloads\billing-system (1)\billing-system"

cd "C:\Users\RAZZ\Downloads\billing-system (1)\supermarket-billing-frontend"

[Link]

import React, { useState } from "react";


import "./[Link]";
import axios from "axios";

const BillingPage = () => {


const [productId, setProductId] = useState("");
const [productName, setProductName] = useState("");
const [price, setPrice] = useState("");
const [gst, setGST] = useState("");
const [quantity, setQuantity] = useState("");
const [billItems, setBillItems] = useState([]);

// Fetch product details when Product ID changes


const handleProductIdChange = async (e) => {
const id = [Link];
setProductId(id);

if (id) {
try {
const response = await
[Link](`[Link]
const product = [Link];

if (product) {
setProductName([Link]);
setPrice([Link]);
setGST([Link]);
} else {
alert("Product not found!");
resetProductFields();
}
} catch (error) {
[Link]("Error fetching product:", error);
alert("Product not found!");
resetProductFields();
}
} else {
resetProductFields();
}
};

// Reset product fields


const resetProductFields = () => {
setProductName("");
setPrice("");
setGST("");
};

// Add product to bill


const handleAddProduct = () => {
if (!productId || !productName || !price || !gst || !quantity) {
alert("Please enter all fields before adding.");
return;
}

if (isNaN(quantity) || quantity <= 0) {


alert("Quantity must be a valid number greater than zero.");
return;
}

const total = (parseFloat(price) + parseFloat(gst)) * parseInt(quantity);


const newItem = {
productId,
name: productName,
quantity: parseInt(quantity),
price: parseFloat(price),
gst: parseFloat(gst),
total
};

setBillItems([...billItems, newItem]);

// Clear input fields after adding


setProductId("");
setProductName("");
setPrice("");
setGST("");
setQuantity("");
};

// Generate bill and send data to backend


const handleGenerateBill = async () => {
if ([Link] === 0) {
alert("No products added to the bill!");
return;
}

const billData = {
products: billItems, // Changed from 'items' to 'products' to match
backend
totalAmount: [Link]((sum, item) => sum + [Link], 0) //
Changed from 'totalPrice' to 'totalAmount'
};

try {
const response = await [Link]("[Link]
billData, {
headers: { "Content-Type": "application/json" }
});

[Link]("Bill generated:", [Link]);


alert("Bill generated successfully!");

setBillItems([]);
} catch (error) {
[Link]("Error generating bill:", error);
alert("Failed to generate bill. Please try again.");
}
};
return (
<div>
<h2>Supermarket Billing System</h2>
<div>
<input type="number" value={productId}
onChange={handleProductIdChange} placeholder="Product ID" />
<input type="text" value={productName} placeholder="Name"
readOnly />
<input type="number" value={quantity} onChange={(e) =>
setQuantity([Link])} placeholder="Quantity" />
<input type="text" value={price} placeholder="Price" readOnly />
<input type="text" value={gst} placeholder="GST" readOnly />
<button onClick={handleAddProduct}>Add Product</button>
</div>
<table>
<thead>
<tr>
<th>Product ID</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>GST</th>
<th>Total</th>
</tr>
</thead>
<tbody>
{[Link]((item, index) => (
<tr key={index}>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
<td>{[Link]}</td>
</tr>
))}
</tbody>
</table>
<button onClick={handleGenerateBill} className="generate-bill-
btn">Generate Bill</button>
</div>
);
};

export default BillingPage;

Common questions

Powered by AI

Importing and using external stylesheets in the BillingPage component allows for centralized styling which promotes consistency and easier maintenance . This integration enhances flexibility when changes across multiple components are needed. However, it may result in CSS conflicts and increased complexity in larger applications if not managed carefully. Implementing scoped CSS methods, such as CSS Modules or Styled Components, could mitigate these issues while ensuring style encapsulation and minimizing unintended side effects.

The method used for clearing input fields in the BillingPage component involves directly setting input states to empty after adding a product to the bill . This approach ensures inputs are reset for new entries, promoting data integrity and preventing accidental duplication. However, it risks clearing data prematurely if an error occurs during the add operation and the item is not appended. Enhanced error-handling mechanisms are recommended to confirm item addition success before resetting fields.

The BillingPage component validates quantity input by ensuring it is a number greater than zero before adding a product to the bill . Potential issues arise if this validation is bypassed or incorrectly implemented, which might result in incorrect billing calculations or missing/bogus data. A more robust validation could involve checking data types and applying constraints on the client and server side to prevent invalid entries, ensuring data integrity and accurate billing.

The BillingPage component updates the state with new bill items using the useState hook, specifically by appending the new item to the existing list of bill items . This approach uses state immutability to ensure updates trigger re-renders for user interface consistency. While effective for small-scale applications, performance implications could occur with large data sets due to frequent state updates triggering excessive re-rendering, potentially slowing down the component. Optimization techniques such as React.memo or component splitting could mitigate these issues.

The asynchronous nature of axios requests in the BillingPage component enables non-blocking operations when fetching product details and submitting bill data, allowing the UI to remain responsive and interactive . This impacts execution flow by deferring certain operations (such as setting state based on response) until the network request has completed, promoting efficient handling of real-time data. However, it requires careful management of promise chains and error handling to ensure continuity and reliability in user interactions.

The BillingPage component handles unsuccessful attempts to fetch product information by logging an error message to the console and alerting the user with 'Product not found!' . This allows users to be informed about the issue and resets the previous product input fields to maintain data integrity. However, the approach could be improved by providing more detailed error messages or alternative actions for the user, improving overall user experience when issues occur.

The BillingPage component handles product data through HTTP requests sent to a local server . Security implications include the potential exposure of sensitive data over unsecured HTTP connections, which could be intercepted by malicious actors. Additionally, the absence of proper authentication or data encryption increases vulnerability to attacks such as man-in-the-middle. To improve security, using HTTPS, implementing authentication, and validating data on the server-side are critical measures.

In the BillingPage component, the total amount for the bill is calculated by summing the total values of each bill item, which are themselves calculated by multiplying each item's (price + gst) by the quantity . This total is stored in a 'totalAmount' property within the 'billData' object. This approach ensures all costs are dynamically aggregated to reflect current billing entries accurately before submitting to the backend for processing.

The useState hook in the BillingPage component allows for managing the local state of React components, enabling interactive functionality such as tracking user inputs and dynamically updating the UI . However, relying solely on useState for state management can lead to limitations in scalability and maintainability, particularly in complex applications. Large applications might benefit from useEffect hooks for side effects and contexts or Redux for global state management to handle state updates more efficiently and predictably across components.

Potential bottlenecks in the BillingPage component when generating a bill include delays due to processing multiple items and network latency in POST requests to the backend . These could significantly affect user experience by causing slow response times. Mitigation strategies include optimizing data operations, such as using efficient data structures for managing bill items, and implementing batching or debouncing techniques to handle input more gracefully. Additionally, adopting a server-side queuing system could distribute load and improve responsiveness.

You might also like