Okay so basically, Im currently making a Web Application with Astro, React and NodeJS.
Im trying to make a dynamic/auto-updated component that will update every few seconds, but right now im having a little problem with even firing the “componentDidMount()” event on a React Component.
This is my React Component Code:
import React, { Component } from 'react';
import './css/PieChart.css';
import {db} from "../utils/db.js";
class PieChart extends Component {
constructor(props) {
super(props);
this.state = {
percentage: 0
}
this.circleRef = React.createRef(); // Create a ref
}
render() {
console.log("Render", this.state.percentage);
return (
<div className="circle rounded-full flex" id="piechart" ref={this.circleRef}>
<p className="z-10">
{this.state.percentage}%
</p>
</div>
);
}
async componentDidMount() {
console.log("ComponentDidMount")
try {
let allDoors = await new Promise((resolve, reject) => {
db.query("SELECT * FROM _doors", function (err, res, fields) {
if (err) reject(err)
resolve(res)
})
})
let openDoors = await new Promise((resolve, reject) => {
db.query("SELECT * FROM _doors WHERE occupied = 1", function (err, res, fields) {
if (err) reject(err)
resolve(res)
})
})
let percentage = openDoors.length / allDoors.length * 100;
this.setState({percentage: percentage});
console.log(percentage)
} catch (error) {
console.error("Error in componentDidMount:", error);
}
}
}
export default PieChart;
This is astros config (astro.config.mjs)
import { defineConfig } from 'astro/config';
import tailwind from "@astrojs/tailwind";
import node from "@astrojs/node";
import auth from "auth-astro";
import react from "@astrojs/react";
export default defineConfig({
integrations: [tailwind(), auth({
providers: []
}), react()],
output: 'hybrid',
outDir: './docs',
build: {
assets: 'astro'
},
adapter: node({
mode: "standalone"
}),
});
This is the DB file which is making a request to my database.
import mysql from 'mysql'
const sql = mysql.createConnection({
host: "host",
user: "user",
password: "password"
})
let db = mysql.createConnection({
host: "host",
user: "user",
password: "password",
database: "database"
});
sql.connect(function (err) {
if (err) {
console.error('Error connecting to the database with sql:', err);
throw err;
}
console.log("Connected with sql!");
let sqlQuery = [
"CREATE DATABASE IF NOT EXISTS autolock",
"CREATE TABLE IF NOT EXISTS _doors (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), floor VARCHAR(255), adminGroupId INT, password VARCHAR(255), rfid VARCHAR(255), status BOOL)",
"CREATE TABLE IF NOT EXISTS _users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), adminGroupId INT, jsId VARCHAR(255))",
"CREATE TABLE IF NOT EXISTS _groups (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))"
]
sql.query(sqlQuery[0], sqlError)
})
db.connect(function (err) {
if (err) {
console.error('Error connecting to the database with db:', err);
throw err;
}
console.log("Connected with db!");
let sqlQuery = [
"CREATE TABLE IF NOT EXISTS _doors (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), floor VARCHAR(255), adminGroupId INT, password VARCHAR(255), rfid VARCHAR(255), status BOOL)",
"CREATE TABLE IF NOT EXISTS _users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), adminGroupId INT, jsId VARCHAR(255))",
"CREATE TABLE IF NOT EXISTS _groups (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))"
]
db.query(sqlQuery[0], sqlError)
db.query(sqlQuery[1], sqlError)
db.query(sqlQuery[2], sqlError)
})
function sqlError(err, result) {
if (err) {
console.error('Error executing query:', err);
throw err;
}
console.log(result)
}
export { sql, db }
In my Index.astro im calling it by just importing it like this.
---
import Layout from "../layouts/Layout.astro";
import DoorTable from "../components/DoorTable.astro";
import PieChartReact from "../components/PieChart.jsx";
import PieChart from "../components/PieChart.astro";
import React from 'react';
---
<Layout title="Welcome to AutoLock.">
<main>
<PieChartReact client:load/>
<DoorTable />
</main>
</Layout>
<style is:global>
:root {
--c: #39463A;
}
main {
margin: 40px;
width: calc(100% - 80px);
max-width: calc(100% - 2rem);
color: white;
font-size: 20px;
line-height: 1.6;
}
</style>
The expected result should be the component’s state at least being modified. (It should be percentage = 100, based on database results, but its not updating)
Pau España Pons is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.