Here's the equivalent React code for the provided function getAverage. Please note that this conversion assumes you're familiar with React basics and have a React project set up with the necessary dependencies, including a Firebase setup for the Firestore database interaction.
Key Changes and Considerations:
Functional Component: The code is wrapped in a functional component named AverageCalculator.
State Management: Since React emphasizes state changes to update the UI, we introduce state for average and scores (equivalent to scoreSecond in your original code).
Lifecycle Method or Hooks: To handle side effects (like database updates and logging averages), we use the useEffect hook, ensuring the function runs after the component mounts or updates.
Firebase Interaction: The Firebase Firestore database interaction remains largely the same, assuming you have db configured similarly in your React context.
DOM Updates: React manages the DOM, so instead of directly updating an element with document.querySelector, we rely on state changes to update the UI.
React Code:
jsx
import React, { useState, useEffect } from 'react';
import { db } from './firebaseConfig'; // Ensure your Firebase config is imported
const AverageCalculator = () => {
const [average, setAverage] = useState(0); // State to store the calculated average
const [scores, setScores] = useState([]); // State to store the array of scores
// Load dummy scores for demonstration (replace with actual data fetching logic)
useEffect(() => {
// Dummy setup for scores
const dummyScores = [85, 90, 78, 92, 88];
setScores(dummyScores);
}, []);
// Calculate average and update Firestore when scores change
useEffect(() => {
if (scores.length > 0) {
calculateAverage();
} else {
// Handle the case when scores array is empty
setAverage(0);
}
}, [scores]);
const calculateAverage = () => {
// Calculate the average score
const sum = scores.reduce((a, b) => a + b, 0);
const avg = sum / scores.length;
setAverage(avg);
updateFirestore(avg, scores);
};
const updateFirestore = (avg, scores) => {
console.log(`Average: ${avg}`);
const collectionRef = db.collection("SinauStudio");
for (let i = 0; i < scores.length; i++) {
const docRef = collectionRef.doc("Eric");
const data = {
[i + 1]: {
score: scores[i],
second: i + 1,
},
};
// Update Firestore with error handling
docRef.update(data).then(() => console.log("Firestore updated successfully"))
.catch(error => console.error("Error updating Firestore:", error));
}
};
return (
<div>
<h2> Average: {average ? average.toFixed(2) : "Calculating..."}</h2>
{/* Optional: Display Scores */}
{scores.length > 0 && (
<div>
<h3>Scores:</h3>
<ul>
{scores.map((score, index) => (
<li key={index}>Score {index + 1}: {score}</li>
))}
</ul>
</div>
)}
</div>
);
};
export default AverageCalculator;
Notes:
Firebase Config: Ensure db is correctly configured and imported from your Firebase setup file.
Score Data: This example uses dummy data for scores. You should replace the dummyScores setup with your actual data fetching or setting logic.
Component Usage: This component, AverageCalculator, can be used within your App's component tree like any other React component.
Error Handling: Error handling is added for Firestore updates to ensure the component remains stable in case of errors.
Edge Cases: The component now handles the case where the scores array is empty, preventing potential division-by-zero errors.