when trying to connect my front end react app to my firebase backend databse, i encountered a problem, when testing the form, i noticed that on the front end, the form is submitted sucessfully, but is not reflected in the database in firebase. the code should work in a way thay on the sales form is filled, the data is sent to the database on firebase, then displayed on the sales record page. below is my code for a SalesForm.js and SalesRecord.js.
// SalesForm.js
//(rest of code)
useEffect(() => {
const fetchUnitPrice = async () => {
try {
// Simulate fetching unit price from a database based on brand, size, and metric
const unitPriceFromDB = await fetchUnitPriceFromDatabase(brand, size, metric);
setUnitPrice(unitPriceFromDB);
} catch (error) {
console.error('Error fetching unit price:', error);
}
};
fetchUnitPrice();
}, [brand, size, metric]);
useEffect(() => {
const calculateTotalPrice = () => {
const quantityValue = parseFloat(quantity) || 0;
const totalPriceValue = unitPrice * quantityValue;
setTotalPrice(totalPriceValue);
};
calculateTotalPrice();
}, [unitPrice, quantity]);
const handleQuantityChange = (e) => {
setQuantity(e.target.value);
};
const handleBrandChange = (e) => {
setBrand(e.target.value);
setSize('');
};
const handleSizeChange = (e) => {
setSize(e.target.value);
};
const handleMetricChange = (e) => {
setMetric(e.target.value);
// Clear quantity when changing metric to avoid conflicts
setQuantity('');
// Fetch unit price based on the selected metric
fetchUnitPrice();
};
const fetchUnitPrice = async () => {
try {
// Simulate fetching unit price from a database based on brand, size, and metric
const unitPriceFromDB = await fetchUnitPriceFromDatabase(brand, size, metric);
setUnitPrice(unitPriceFromDB);
} catch (error) {
console.error('Error fetching unit price:', error);
}
};
const handleRemarksChange = (e) => {
setRemarks(e.target.value);
};
// Inside handleSubmit function in SalesForm.js
const handleSubmit = (e) => {
e.preventDefault();
const shouldSubmit = window.confirm('Are you sure you want to submit this sale?');
if (shouldSubmit) {
console.log('Form submitted:', { brand, size, quantity, metric, unitPrice, totalPrice, remarks });
// ... Other code to store data in Firestore or your database ...
setBrand('');
setSize('');
setQuantity('');
setMetric('Bag');
setUnitPrice(0);
setTotalPrice(0);
setRemarks('');
}
};
// (rest of code)
export default SalesForm;
//SalesRecord
import { useState, useEffect } from "react";
import { collection, getDocs, setDoc, doc } from "firebase/firestore";
import {db} from '../../firebase.js'
export const SalesRecord = () => {
// State for holding sales records data
const [salesRecords, setSalesRecords] = useState([]);
// Loading state to track whether data is being fetched
const [loading, setLoading] = useState(true);
// Error state to handle any potential errors during data fetching
const [error, setError] = useState(null);
// useEffect hook to fetch data when the component mounts
useEffect(() => {
const fetchData = async () => {
try {
// Temporary array to store fetched data
const response = [];
// Reference to the Firestore collection
const collectionPath = collection(db, 'SalesRecord');
// Fetch data from the Firestore collection
const querySnapshot = await getDocs(collectionPath);
// Loop through each document and extract data
querySnapshot.forEach((doc) => {
response.push({
id: doc.id,
...doc.data(),
});
});
// Set the state with the fetched data
setSalesRecords(response);
// Set loading to false once data is fetched
setLoading(false);
// Add a new document to the SalesRecord collection
await setDoc(doc(collectionPath, "nFwMNRZK72nFo2snlaPw"), {
brand: "ACEFloat",
size: "7mm",
quantity: 4,
metric: "Bag",
unitPrice: 23987,
totalPrice: 34989,
date: new Date().toISOString(), // Use the current date
remark:"hey there"
});
// Fetch the data again after adding the new document
const updatedQuerySnapshot = await getDocs(collectionPath);
// Update the state with the latest data
const updatedResponse = updatedQuerySnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
setSalesRecords(updatedResponse);
} catch (error) {
// Handle any errors that occur during data fetching
console.error("Error fetching or updating data:", error);
setError("An error occurred while fetching or updating data.");
// Set loading to false in case of an error
setLoading(false);
}
};
// Call the fetchData function when the component mounts
fetchData();
}, []); // Empty dependency array means this effect runs once on mount
// Loading state: Show a loading message while data is being fetched
if (loading) {
return <p>Loading...</p>;
}
// Error state: Display an error message if data fetching encounters an issue
if (error) {
return <p>Error: {error}</p>;
}
//{rest of code}
export default SalesRecord;
i intitally thought it was how i implemented the “useEffect”, i then followed the firebase documentation, all proved to no effect.
The code you’re showing in
handleSubmit
doesn’t have any code at all that deals with a database. There is just a comment that says “… Other code to store data in Firestore or your database …” I think you need to do some debugging to trace how your code working, and be more clear what specifically you found is not working the way you expect.