I have filtered out procedures that I am interested on, and now want to display their average patient_cost. I have the calculation working, but am unsure how to display it in the screen for users to see it. This is what I have:
import React, { useState, useEffect, useMemo } from "react";
function Average ({posts, setUser, user}){
const [procedures, setProcedures] = useState ([])
const [filteredProcedure, setFilteredProcedure] = useState ("")
const [averageCost, setAverageCost] = useState (0)
const uniques = procedures.map(procedure => procedure.procedure)
.filter((value, index, self) => self.indexOf(value) === index )
useEffect(() => {
fetch(`/posts/${procedures}`)
.then((r) => r.json())
.then(setProcedures);
}, [posts]);
function handleProcedureChange(procedure) {
setFilteredProcedure(procedure);
let filteredObject = procedures.filter (p=> p.procedure === procedure)
console.log("lenght of filtered procedure:", filteredObject)
let total = 0;
for (let ii = 0; ii < filteredObject.length; ii++) {
total = total + filteredObject[ii].patient_cost
}
console.log("total:", total)
let avg = total / filteredObject.length
console.log("average:", avg)
}
function handleChange(e) {
handleProcedureChange(e.target.value);
console.log(e.target.value)
}
return (
<div >
<div >
<label htmlFor="procedure">Procedure:</label>
<select
id="procedure"
name="procedure"
value={filteredProcedure}
onChange={handleChange} >
<option>Select Procedure</option>
{uniques.map((procedure) => (
<option key={procedure} value={procedure}>
{procedure}
</option>
))}
</select>
</div>
average: {averageCost}
</div>
)
}
export default Average;
How can I tie the “let avg = total / filteredObject.length” to the state “average: {averageCost}” at the end? I’m new at this and do not know if there is a better way to write this code.
Appreciate the help here.