On React (Next.js), I am trying to make a counter for adding records to the PostgreSQL database (>30,000 records) (for import from EXELL). The addition procedure works quite quickly, but I still want to make a counter that would be displayed when this procedure is launched and output the current record. In my code, the counter is output to console.log , but not rendered on the screen. And it is not displayed in either when insertRows.current > 0 or when setIsInsert(true). What is wrong, and whether it can be implemented somehow. I wanted to use useEffect() , but I think it's only used when getting data before the initial rendering. I guess I still don't know much about Refct? Please help implement this, or suggest something else to
import { useEffect, useState, useRef } from "react"
export default function insertCounter() {
const insertRows = useRef(0) //number of inserted records
const [insRows, setInsRows] = useState(0) //number of inserted records
//const [isInsert, setIsInsert] = useState(true) // Visual ProgressBar
const data = [
{ id: 1, name: "Roman" },
{ id: 2, name: "Misha" },
{ id: 3, name: "Vova" },
]
const addRows = (data) => {
try {
data.forEach((row) => {
// const cInsert = insertToPSQL(row) //Insert record to PostgreSQL (async function)
insertRows.current = insertRows.current + 1
setInsRows(insRows+1)
console.log("insertRows.current=", insertRows.current)
console.log("insRows=", insRows)
})
} finally {
console.log("insertCounter.js/addRows/finally/insertRows.current=", insertRows.current)
alert(`finally:Added ${insertRows.current}`)
insertRows.current = 0
setInsRows(0)
}
}
const handleInsert = () => {
insertRows.current = 0
// setIsInsert(true)
addRows(data)
}
useEffect(() => {
//?????????????????? /
}, [])
return (
<div style={{ textAlign: "center", color: "blue" }}>
<h2 style={{ color: "red" }}>insertCounter</h2>
<button onClick={handleInsert} style={{ color: "yellow", backgroundColor: "blue" }}>
Insert
</button>
{<div>Added records:{insertRows.current} </div>}
{<div>Added records:{insRows} </div>}
</div>
)
}